]> git.ipfire.org Git - thirdparty/git.git/blob - merge-recursive.c
treewide: be explicit about dependence on gettext.h
[thirdparty/git.git] / merge-recursive.c
1 /*
2 * Recursive Merge algorithm stolen from git-merge-recursive.py by
3 * Fredrik Kuivinen.
4 * The thieves were Alex Riesen and Johannes Schindelin, in June/July 2006
5 */
6 #include "cache.h"
7 #include "merge-recursive.h"
8
9 #include "advice.h"
10 #include "alloc.h"
11 #include "attr.h"
12 #include "blob.h"
13 #include "cache-tree.h"
14 #include "commit.h"
15 #include "commit-reach.h"
16 #include "config.h"
17 #include "diff.h"
18 #include "diffcore.h"
19 #include "dir.h"
20 #include "gettext.h"
21 #include "hex.h"
22 #include "ll-merge.h"
23 #include "lockfile.h"
24 #include "object-store.h"
25 #include "repository.h"
26 #include "revision.h"
27 #include "string-list.h"
28 #include "submodule-config.h"
29 #include "submodule.h"
30 #include "tag.h"
31 #include "tree-walk.h"
32 #include "unpack-trees.h"
33 #include "xdiff-interface.h"
34
35 struct merge_options_internal {
36 int call_depth;
37 int needed_rename_limit;
38 struct hashmap current_file_dir_set;
39 struct string_list df_conflict_file_set;
40 struct unpack_trees_options unpack_opts;
41 struct index_state orig_index;
42 };
43
44 struct path_hashmap_entry {
45 struct hashmap_entry e;
46 char path[FLEX_ARRAY];
47 };
48
49 static int path_hashmap_cmp(const void *cmp_data UNUSED,
50 const struct hashmap_entry *eptr,
51 const struct hashmap_entry *entry_or_key,
52 const void *keydata)
53 {
54 const struct path_hashmap_entry *a, *b;
55 const char *key = keydata;
56
57 a = container_of(eptr, const struct path_hashmap_entry, e);
58 b = container_of(entry_or_key, const struct path_hashmap_entry, e);
59
60 return fspathcmp(a->path, key ? key : b->path);
61 }
62
63 /*
64 * For dir_rename_entry, directory names are stored as a full path from the
65 * toplevel of the repository and do not include a trailing '/'. Also:
66 *
67 * dir: original name of directory being renamed
68 * non_unique_new_dir: if true, could not determine new_dir
69 * new_dir: final name of directory being renamed
70 * possible_new_dirs: temporary used to help determine new_dir; see comments
71 * in get_directory_renames() for details
72 */
73 struct dir_rename_entry {
74 struct hashmap_entry ent;
75 char *dir;
76 unsigned non_unique_new_dir:1;
77 struct strbuf new_dir;
78 struct string_list possible_new_dirs;
79 };
80
81 static struct dir_rename_entry *dir_rename_find_entry(struct hashmap *hashmap,
82 char *dir)
83 {
84 struct dir_rename_entry key;
85
86 if (!dir)
87 return NULL;
88 hashmap_entry_init(&key.ent, strhash(dir));
89 key.dir = dir;
90 return hashmap_get_entry(hashmap, &key, ent, NULL);
91 }
92
93 static int dir_rename_cmp(const void *cmp_data UNUSED,
94 const struct hashmap_entry *eptr,
95 const struct hashmap_entry *entry_or_key,
96 const void *keydata UNUSED)
97 {
98 const struct dir_rename_entry *e1, *e2;
99
100 e1 = container_of(eptr, const struct dir_rename_entry, ent);
101 e2 = container_of(entry_or_key, const struct dir_rename_entry, ent);
102
103 return strcmp(e1->dir, e2->dir);
104 }
105
106 static void dir_rename_init(struct hashmap *map)
107 {
108 hashmap_init(map, dir_rename_cmp, NULL, 0);
109 }
110
111 static void dir_rename_entry_init(struct dir_rename_entry *entry,
112 char *directory)
113 {
114 hashmap_entry_init(&entry->ent, strhash(directory));
115 entry->dir = directory;
116 entry->non_unique_new_dir = 0;
117 strbuf_init(&entry->new_dir, 0);
118 string_list_init_nodup(&entry->possible_new_dirs);
119 }
120
121 struct collision_entry {
122 struct hashmap_entry ent;
123 char *target_file;
124 struct string_list source_files;
125 unsigned reported_already:1;
126 };
127
128 static struct collision_entry *collision_find_entry(struct hashmap *hashmap,
129 char *target_file)
130 {
131 struct collision_entry key;
132
133 hashmap_entry_init(&key.ent, strhash(target_file));
134 key.target_file = target_file;
135 return hashmap_get_entry(hashmap, &key, ent, NULL);
136 }
137
138 static int collision_cmp(const void *cmp_data UNUSED,
139 const struct hashmap_entry *eptr,
140 const struct hashmap_entry *entry_or_key,
141 const void *keydata UNUSED)
142 {
143 const struct collision_entry *e1, *e2;
144
145 e1 = container_of(eptr, const struct collision_entry, ent);
146 e2 = container_of(entry_or_key, const struct collision_entry, ent);
147
148 return strcmp(e1->target_file, e2->target_file);
149 }
150
151 static void collision_init(struct hashmap *map)
152 {
153 hashmap_init(map, collision_cmp, NULL, 0);
154 }
155
156 static void flush_output(struct merge_options *opt)
157 {
158 if (opt->buffer_output < 2 && opt->obuf.len) {
159 fputs(opt->obuf.buf, stdout);
160 strbuf_reset(&opt->obuf);
161 }
162 }
163
164 __attribute__((format (printf, 2, 3)))
165 static int err(struct merge_options *opt, const char *err, ...)
166 {
167 va_list params;
168
169 if (opt->buffer_output < 2)
170 flush_output(opt);
171 else {
172 strbuf_complete(&opt->obuf, '\n');
173 strbuf_addstr(&opt->obuf, "error: ");
174 }
175 va_start(params, err);
176 strbuf_vaddf(&opt->obuf, err, params);
177 va_end(params);
178 if (opt->buffer_output > 1)
179 strbuf_addch(&opt->obuf, '\n');
180 else {
181 error("%s", opt->obuf.buf);
182 strbuf_reset(&opt->obuf);
183 }
184
185 return -1;
186 }
187
188 static struct tree *shift_tree_object(struct repository *repo,
189 struct tree *one, struct tree *two,
190 const char *subtree_shift)
191 {
192 struct object_id shifted;
193
194 if (!*subtree_shift) {
195 shift_tree(repo, &one->object.oid, &two->object.oid, &shifted, 0);
196 } else {
197 shift_tree_by(repo, &one->object.oid, &two->object.oid, &shifted,
198 subtree_shift);
199 }
200 if (oideq(&two->object.oid, &shifted))
201 return two;
202 return lookup_tree(repo, &shifted);
203 }
204
205 static inline void set_commit_tree(struct commit *c, struct tree *t)
206 {
207 c->maybe_tree = t;
208 }
209
210 static struct commit *make_virtual_commit(struct repository *repo,
211 struct tree *tree,
212 const char *comment)
213 {
214 struct commit *commit = alloc_commit_node(repo);
215
216 set_merge_remote_desc(commit, comment, (struct object *)commit);
217 set_commit_tree(commit, tree);
218 commit->object.parsed = 1;
219 return commit;
220 }
221
222 enum rename_type {
223 RENAME_NORMAL = 0,
224 RENAME_VIA_DIR,
225 RENAME_ADD,
226 RENAME_DELETE,
227 RENAME_ONE_FILE_TO_ONE,
228 RENAME_ONE_FILE_TO_TWO,
229 RENAME_TWO_FILES_TO_ONE
230 };
231
232 /*
233 * Since we want to write the index eventually, we cannot reuse the index
234 * for these (temporary) data.
235 */
236 struct stage_data {
237 struct diff_filespec stages[4]; /* mostly for oid & mode; maybe path */
238 struct rename_conflict_info *rename_conflict_info;
239 unsigned processed:1;
240 };
241
242 struct rename {
243 unsigned processed:1;
244 struct diff_filepair *pair;
245 const char *branch; /* branch that the rename occurred on */
246 /*
247 * If directory rename detection affected this rename, what was its
248 * original type ('A' or 'R') and it's original destination before
249 * the directory rename (otherwise, '\0' and NULL for these two vars).
250 */
251 char dir_rename_original_type;
252 char *dir_rename_original_dest;
253 /*
254 * Purpose of src_entry and dst_entry:
255 *
256 * If 'before' is renamed to 'after' then src_entry will contain
257 * the versions of 'before' from the merge_base, HEAD, and MERGE in
258 * stages 1, 2, and 3; dst_entry will contain the respective
259 * versions of 'after' in corresponding locations. Thus, we have a
260 * total of six modes and oids, though some will be null. (Stage 0
261 * is ignored; we're interested in handling conflicts.)
262 *
263 * Since we don't turn on break-rewrites by default, neither
264 * src_entry nor dst_entry can have all three of their stages have
265 * non-null oids, meaning at most four of the six will be non-null.
266 * Also, since this is a rename, both src_entry and dst_entry will
267 * have at least one non-null oid, meaning at least two will be
268 * non-null. Of the six oids, a typical rename will have three be
269 * non-null. Only two implies a rename/delete, and four implies a
270 * rename/add.
271 */
272 struct stage_data *src_entry;
273 struct stage_data *dst_entry;
274 };
275
276 struct rename_conflict_info {
277 enum rename_type rename_type;
278 struct rename *ren1;
279 struct rename *ren2;
280 };
281
282 static inline void setup_rename_conflict_info(enum rename_type rename_type,
283 struct merge_options *opt,
284 struct rename *ren1,
285 struct rename *ren2)
286 {
287 struct rename_conflict_info *ci;
288
289 /*
290 * When we have two renames involved, it's easiest to get the
291 * correct things into stage 2 and 3, and to make sure that the
292 * content merge puts HEAD before the other branch if we just
293 * ensure that branch1 == opt->branch1. So, simply flip arguments
294 * around if we don't have that.
295 */
296 if (ren2 && ren1->branch != opt->branch1) {
297 setup_rename_conflict_info(rename_type, opt, ren2, ren1);
298 return;
299 }
300
301 CALLOC_ARRAY(ci, 1);
302 ci->rename_type = rename_type;
303 ci->ren1 = ren1;
304 ci->ren2 = ren2;
305
306 ci->ren1->dst_entry->processed = 0;
307 ci->ren1->dst_entry->rename_conflict_info = ci;
308 if (ren2) {
309 ci->ren2->dst_entry->rename_conflict_info = ci;
310 }
311 }
312
313 static int show(struct merge_options *opt, int v)
314 {
315 return (!opt->priv->call_depth && opt->verbosity >= v) ||
316 opt->verbosity >= 5;
317 }
318
319 __attribute__((format (printf, 3, 4)))
320 static void output(struct merge_options *opt, int v, const char *fmt, ...)
321 {
322 va_list ap;
323
324 if (!show(opt, v))
325 return;
326
327 strbuf_addchars(&opt->obuf, ' ', opt->priv->call_depth * 2);
328
329 va_start(ap, fmt);
330 strbuf_vaddf(&opt->obuf, fmt, ap);
331 va_end(ap);
332
333 strbuf_addch(&opt->obuf, '\n');
334 if (!opt->buffer_output)
335 flush_output(opt);
336 }
337
338 static void repo_output_commit_title(struct merge_options *opt,
339 struct repository *repo,
340 struct commit *commit)
341 {
342 struct merge_remote_desc *desc;
343
344 strbuf_addchars(&opt->obuf, ' ', opt->priv->call_depth * 2);
345 desc = merge_remote_util(commit);
346 if (desc)
347 strbuf_addf(&opt->obuf, "virtual %s\n", desc->name);
348 else {
349 strbuf_repo_add_unique_abbrev(&opt->obuf, repo,
350 &commit->object.oid,
351 DEFAULT_ABBREV);
352 strbuf_addch(&opt->obuf, ' ');
353 if (repo_parse_commit(repo, commit) != 0)
354 strbuf_addstr(&opt->obuf, _("(bad commit)\n"));
355 else {
356 const char *title;
357 const char *msg = repo_get_commit_buffer(repo, commit, NULL);
358 int len = find_commit_subject(msg, &title);
359 if (len)
360 strbuf_addf(&opt->obuf, "%.*s\n", len, title);
361 repo_unuse_commit_buffer(repo, commit, msg);
362 }
363 }
364 flush_output(opt);
365 }
366
367 static void output_commit_title(struct merge_options *opt, struct commit *commit)
368 {
369 repo_output_commit_title(opt, the_repository, commit);
370 }
371
372 static int add_cacheinfo(struct merge_options *opt,
373 const struct diff_filespec *blob,
374 const char *path, int stage, int refresh, int options)
375 {
376 struct index_state *istate = opt->repo->index;
377 struct cache_entry *ce;
378 int ret;
379
380 ce = make_cache_entry(istate, blob->mode, &blob->oid, path, stage, 0);
381 if (!ce)
382 return err(opt, _("add_cacheinfo failed for path '%s'; merge aborting."), path);
383
384 ret = add_index_entry(istate, ce, options);
385 if (refresh) {
386 struct cache_entry *nce;
387
388 nce = refresh_cache_entry(istate, ce,
389 CE_MATCH_REFRESH | CE_MATCH_IGNORE_MISSING);
390 if (!nce)
391 return err(opt, _("add_cacheinfo failed to refresh for path '%s'; merge aborting."), path);
392 if (nce != ce)
393 ret = add_index_entry(istate, nce, options);
394 }
395 return ret;
396 }
397
398 static inline int merge_detect_rename(struct merge_options *opt)
399 {
400 return (opt->detect_renames >= 0) ? opt->detect_renames : 1;
401 }
402
403 static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree)
404 {
405 parse_tree(tree);
406 init_tree_desc(desc, tree->buffer, tree->size);
407 }
408
409 static int unpack_trees_start(struct merge_options *opt,
410 struct tree *common,
411 struct tree *head,
412 struct tree *merge)
413 {
414 int rc;
415 struct tree_desc t[3];
416 struct index_state tmp_index = INDEX_STATE_INIT(opt->repo);
417
418 memset(&opt->priv->unpack_opts, 0, sizeof(opt->priv->unpack_opts));
419 if (opt->priv->call_depth)
420 opt->priv->unpack_opts.index_only = 1;
421 else {
422 opt->priv->unpack_opts.update = 1;
423 /* FIXME: should only do this if !overwrite_ignore */
424 opt->priv->unpack_opts.preserve_ignored = 0;
425 }
426 opt->priv->unpack_opts.merge = 1;
427 opt->priv->unpack_opts.head_idx = 2;
428 opt->priv->unpack_opts.fn = threeway_merge;
429 opt->priv->unpack_opts.src_index = opt->repo->index;
430 opt->priv->unpack_opts.dst_index = &tmp_index;
431 opt->priv->unpack_opts.aggressive = !merge_detect_rename(opt);
432 setup_unpack_trees_porcelain(&opt->priv->unpack_opts, "merge");
433
434 init_tree_desc_from_tree(t+0, common);
435 init_tree_desc_from_tree(t+1, head);
436 init_tree_desc_from_tree(t+2, merge);
437
438 rc = unpack_trees(3, t, &opt->priv->unpack_opts);
439 cache_tree_free(&opt->repo->index->cache_tree);
440
441 /*
442 * Update opt->repo->index to match the new results, AFTER saving a
443 * copy in opt->priv->orig_index. Update src_index to point to the
444 * saved copy. (verify_uptodate() checks src_index, and the original
445 * index is the one that had the necessary modification timestamps.)
446 */
447 opt->priv->orig_index = *opt->repo->index;
448 *opt->repo->index = tmp_index;
449 opt->priv->unpack_opts.src_index = &opt->priv->orig_index;
450
451 return rc;
452 }
453
454 static void unpack_trees_finish(struct merge_options *opt)
455 {
456 discard_index(&opt->priv->orig_index);
457 clear_unpack_trees_porcelain(&opt->priv->unpack_opts);
458 }
459
460 static int save_files_dirs(const struct object_id *oid UNUSED,
461 struct strbuf *base, const char *path,
462 unsigned int mode, void *context)
463 {
464 struct path_hashmap_entry *entry;
465 int baselen = base->len;
466 struct merge_options *opt = context;
467
468 strbuf_addstr(base, path);
469
470 FLEX_ALLOC_MEM(entry, path, base->buf, base->len);
471 hashmap_entry_init(&entry->e, fspathhash(entry->path));
472 hashmap_add(&opt->priv->current_file_dir_set, &entry->e);
473
474 strbuf_setlen(base, baselen);
475 return (S_ISDIR(mode) ? READ_TREE_RECURSIVE : 0);
476 }
477
478 static void get_files_dirs(struct merge_options *opt, struct tree *tree)
479 {
480 struct pathspec match_all;
481 memset(&match_all, 0, sizeof(match_all));
482 read_tree(opt->repo, tree,
483 &match_all, save_files_dirs, opt);
484 }
485
486 static int get_tree_entry_if_blob(struct repository *r,
487 const struct object_id *tree,
488 const char *path,
489 struct diff_filespec *dfs)
490 {
491 int ret;
492
493 ret = get_tree_entry(r, tree, path, &dfs->oid, &dfs->mode);
494 if (S_ISDIR(dfs->mode)) {
495 oidcpy(&dfs->oid, null_oid());
496 dfs->mode = 0;
497 }
498 return ret;
499 }
500
501 /*
502 * Returns an index_entry instance which doesn't have to correspond to
503 * a real cache entry in Git's index.
504 */
505 static struct stage_data *insert_stage_data(struct repository *r,
506 const char *path,
507 struct tree *o, struct tree *a, struct tree *b,
508 struct string_list *entries)
509 {
510 struct string_list_item *item;
511 struct stage_data *e = xcalloc(1, sizeof(struct stage_data));
512 get_tree_entry_if_blob(r, &o->object.oid, path, &e->stages[1]);
513 get_tree_entry_if_blob(r, &a->object.oid, path, &e->stages[2]);
514 get_tree_entry_if_blob(r, &b->object.oid, path, &e->stages[3]);
515 item = string_list_insert(entries, path);
516 item->util = e;
517 return e;
518 }
519
520 /*
521 * Create a dictionary mapping file names to stage_data objects. The
522 * dictionary contains one entry for every path with a non-zero stage entry.
523 */
524 static struct string_list *get_unmerged(struct index_state *istate)
525 {
526 struct string_list *unmerged = xmalloc(sizeof(struct string_list));
527 int i;
528
529 string_list_init_dup(unmerged);
530
531 /* TODO: audit for interaction with sparse-index. */
532 ensure_full_index(istate);
533 for (i = 0; i < istate->cache_nr; i++) {
534 struct string_list_item *item;
535 struct stage_data *e;
536 const struct cache_entry *ce = istate->cache[i];
537 if (!ce_stage(ce))
538 continue;
539
540 item = string_list_lookup(unmerged, ce->name);
541 if (!item) {
542 item = string_list_insert(unmerged, ce->name);
543 item->util = xcalloc(1, sizeof(struct stage_data));
544 }
545 e = item->util;
546 e->stages[ce_stage(ce)].mode = ce->ce_mode;
547 oidcpy(&e->stages[ce_stage(ce)].oid, &ce->oid);
548 }
549
550 return unmerged;
551 }
552
553 static int string_list_df_name_compare(const char *one, const char *two)
554 {
555 int onelen = strlen(one);
556 int twolen = strlen(two);
557 /*
558 * Here we only care that entries for D/F conflicts are
559 * adjacent, in particular with the file of the D/F conflict
560 * appearing before files below the corresponding directory.
561 * The order of the rest of the list is irrelevant for us.
562 *
563 * To achieve this, we sort with df_name_compare and provide
564 * the mode S_IFDIR so that D/F conflicts will sort correctly.
565 * We use the mode S_IFDIR for everything else for simplicity,
566 * since in other cases any changes in their order due to
567 * sorting cause no problems for us.
568 */
569 int cmp = df_name_compare(one, onelen, S_IFDIR,
570 two, twolen, S_IFDIR);
571 /*
572 * Now that 'foo' and 'foo/bar' compare equal, we have to make sure
573 * that 'foo' comes before 'foo/bar'.
574 */
575 if (cmp)
576 return cmp;
577 return onelen - twolen;
578 }
579
580 static void record_df_conflict_files(struct merge_options *opt,
581 struct string_list *entries)
582 {
583 /* If there is a D/F conflict and the file for such a conflict
584 * currently exists in the working tree, we want to allow it to be
585 * removed to make room for the corresponding directory if needed.
586 * The files underneath the directories of such D/F conflicts will
587 * be processed before the corresponding file involved in the D/F
588 * conflict. If the D/F directory ends up being removed by the
589 * merge, then we won't have to touch the D/F file. If the D/F
590 * directory needs to be written to the working copy, then the D/F
591 * file will simply be removed (in make_room_for_path()) to make
592 * room for the necessary paths. Note that if both the directory
593 * and the file need to be present, then the D/F file will be
594 * reinstated with a new unique name at the time it is processed.
595 */
596 struct string_list df_sorted_entries = STRING_LIST_INIT_NODUP;
597 const char *last_file = NULL;
598 int last_len = 0;
599 int i;
600
601 /*
602 * If we're merging merge-bases, we don't want to bother with
603 * any working directory changes.
604 */
605 if (opt->priv->call_depth)
606 return;
607
608 /* Ensure D/F conflicts are adjacent in the entries list. */
609 for (i = 0; i < entries->nr; i++) {
610 struct string_list_item *next = &entries->items[i];
611 string_list_append(&df_sorted_entries, next->string)->util =
612 next->util;
613 }
614 df_sorted_entries.cmp = string_list_df_name_compare;
615 string_list_sort(&df_sorted_entries);
616
617 string_list_clear(&opt->priv->df_conflict_file_set, 1);
618 for (i = 0; i < df_sorted_entries.nr; i++) {
619 const char *path = df_sorted_entries.items[i].string;
620 int len = strlen(path);
621 struct stage_data *e = df_sorted_entries.items[i].util;
622
623 /*
624 * Check if last_file & path correspond to a D/F conflict;
625 * i.e. whether path is last_file+'/'+<something>.
626 * If so, record that it's okay to remove last_file to make
627 * room for path and friends if needed.
628 */
629 if (last_file &&
630 len > last_len &&
631 memcmp(path, last_file, last_len) == 0 &&
632 path[last_len] == '/') {
633 string_list_insert(&opt->priv->df_conflict_file_set, last_file);
634 }
635
636 /*
637 * Determine whether path could exist as a file in the
638 * working directory as a possible D/F conflict. This
639 * will only occur when it exists in stage 2 as a
640 * file.
641 */
642 if (S_ISREG(e->stages[2].mode) || S_ISLNK(e->stages[2].mode)) {
643 last_file = path;
644 last_len = len;
645 } else {
646 last_file = NULL;
647 }
648 }
649 string_list_clear(&df_sorted_entries, 0);
650 }
651
652 static int update_stages(struct merge_options *opt, const char *path,
653 const struct diff_filespec *o,
654 const struct diff_filespec *a,
655 const struct diff_filespec *b)
656 {
657
658 /*
659 * NOTE: It is usually a bad idea to call update_stages on a path
660 * before calling update_file on that same path, since it can
661 * sometimes lead to spurious "refusing to lose untracked file..."
662 * messages from update_file (via make_room_for path via
663 * would_lose_untracked). Instead, reverse the order of the calls
664 * (executing update_file first and then update_stages).
665 */
666 int clear = 1;
667 int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_SKIP_DFCHECK;
668 if (clear)
669 if (remove_file_from_index(opt->repo->index, path))
670 return -1;
671 if (o)
672 if (add_cacheinfo(opt, o, path, 1, 0, options))
673 return -1;
674 if (a)
675 if (add_cacheinfo(opt, a, path, 2, 0, options))
676 return -1;
677 if (b)
678 if (add_cacheinfo(opt, b, path, 3, 0, options))
679 return -1;
680 return 0;
681 }
682
683 static void update_entry(struct stage_data *entry,
684 struct diff_filespec *o,
685 struct diff_filespec *a,
686 struct diff_filespec *b)
687 {
688 entry->processed = 0;
689 entry->stages[1].mode = o->mode;
690 entry->stages[2].mode = a->mode;
691 entry->stages[3].mode = b->mode;
692 oidcpy(&entry->stages[1].oid, &o->oid);
693 oidcpy(&entry->stages[2].oid, &a->oid);
694 oidcpy(&entry->stages[3].oid, &b->oid);
695 }
696
697 static int remove_file(struct merge_options *opt, int clean,
698 const char *path, int no_wd)
699 {
700 int update_cache = opt->priv->call_depth || clean;
701 int update_working_directory = !opt->priv->call_depth && !no_wd;
702
703 if (update_cache) {
704 if (remove_file_from_index(opt->repo->index, path))
705 return -1;
706 }
707 if (update_working_directory) {
708 if (ignore_case) {
709 struct cache_entry *ce;
710 ce = index_file_exists(opt->repo->index, path, strlen(path),
711 ignore_case);
712 if (ce && ce_stage(ce) == 0 && strcmp(path, ce->name))
713 return 0;
714 }
715 if (remove_path(path))
716 return -1;
717 }
718 return 0;
719 }
720
721 /* add a string to a strbuf, but converting "/" to "_" */
722 static void add_flattened_path(struct strbuf *out, const char *s)
723 {
724 size_t i = out->len;
725 strbuf_addstr(out, s);
726 for (; i < out->len; i++)
727 if (out->buf[i] == '/')
728 out->buf[i] = '_';
729 }
730
731 static char *unique_path(struct merge_options *opt,
732 const char *path,
733 const char *branch)
734 {
735 struct path_hashmap_entry *entry;
736 struct strbuf newpath = STRBUF_INIT;
737 int suffix = 0;
738 size_t base_len;
739
740 strbuf_addf(&newpath, "%s~", path);
741 add_flattened_path(&newpath, branch);
742
743 base_len = newpath.len;
744 while (hashmap_get_from_hash(&opt->priv->current_file_dir_set,
745 fspathhash(newpath.buf), newpath.buf) ||
746 (!opt->priv->call_depth && file_exists(newpath.buf))) {
747 strbuf_setlen(&newpath, base_len);
748 strbuf_addf(&newpath, "_%d", suffix++);
749 }
750
751 FLEX_ALLOC_MEM(entry, path, newpath.buf, newpath.len);
752 hashmap_entry_init(&entry->e, fspathhash(entry->path));
753 hashmap_add(&opt->priv->current_file_dir_set, &entry->e);
754 return strbuf_detach(&newpath, NULL);
755 }
756
757 /**
758 * Check whether a directory in the index is in the way of an incoming
759 * file. Return 1 if so. If check_working_copy is non-zero, also
760 * check the working directory. If empty_ok is non-zero, also return
761 * 0 in the case where the working-tree dir exists but is empty.
762 */
763 static int dir_in_way(struct index_state *istate, const char *path,
764 int check_working_copy, int empty_ok)
765 {
766 int pos;
767 struct strbuf dirpath = STRBUF_INIT;
768 struct stat st;
769
770 strbuf_addstr(&dirpath, path);
771 strbuf_addch(&dirpath, '/');
772
773 pos = index_name_pos(istate, dirpath.buf, dirpath.len);
774
775 if (pos < 0)
776 pos = -1 - pos;
777 if (pos < istate->cache_nr &&
778 !strncmp(dirpath.buf, istate->cache[pos]->name, dirpath.len)) {
779 strbuf_release(&dirpath);
780 return 1;
781 }
782
783 strbuf_release(&dirpath);
784 return check_working_copy && !lstat(path, &st) && S_ISDIR(st.st_mode) &&
785 !(empty_ok && is_empty_dir(path)) &&
786 !has_symlink_leading_path(path, strlen(path));
787 }
788
789 /*
790 * Returns whether path was tracked in the index before the merge started,
791 * and its oid and mode match the specified values
792 */
793 static int was_tracked_and_matches(struct merge_options *opt, const char *path,
794 const struct diff_filespec *blob)
795 {
796 int pos = index_name_pos(&opt->priv->orig_index, path, strlen(path));
797 struct cache_entry *ce;
798
799 if (0 > pos)
800 /* we were not tracking this path before the merge */
801 return 0;
802
803 /* See if the file we were tracking before matches */
804 ce = opt->priv->orig_index.cache[pos];
805 return (oideq(&ce->oid, &blob->oid) && ce->ce_mode == blob->mode);
806 }
807
808 /*
809 * Returns whether path was tracked in the index before the merge started
810 */
811 static int was_tracked(struct merge_options *opt, const char *path)
812 {
813 int pos = index_name_pos(&opt->priv->orig_index, path, strlen(path));
814
815 if (0 <= pos)
816 /* we were tracking this path before the merge */
817 return 1;
818
819 return 0;
820 }
821
822 static int would_lose_untracked(struct merge_options *opt, const char *path)
823 {
824 struct index_state *istate = opt->repo->index;
825
826 /*
827 * This may look like it can be simplified to:
828 * return !was_tracked(opt, path) && file_exists(path)
829 * but it can't. This function needs to know whether path was in
830 * the working tree due to EITHER having been tracked in the index
831 * before the merge OR having been put into the working copy and
832 * index by unpack_trees(). Due to that either-or requirement, we
833 * check the current index instead of the original one.
834 *
835 * Note that we do not need to worry about merge-recursive itself
836 * updating the index after unpack_trees() and before calling this
837 * function, because we strictly require all code paths in
838 * merge-recursive to update the working tree first and the index
839 * second. Doing otherwise would break
840 * update_file()/would_lose_untracked(); see every comment in this
841 * file which mentions "update_stages".
842 */
843 int pos = index_name_pos(istate, path, strlen(path));
844
845 if (pos < 0)
846 pos = -1 - pos;
847 while (pos < istate->cache_nr &&
848 !strcmp(path, istate->cache[pos]->name)) {
849 /*
850 * If stage #0, it is definitely tracked.
851 * If it has stage #2 then it was tracked
852 * before this merge started. All other
853 * cases the path was not tracked.
854 */
855 switch (ce_stage(istate->cache[pos])) {
856 case 0:
857 case 2:
858 return 0;
859 }
860 pos++;
861 }
862 return file_exists(path);
863 }
864
865 static int was_dirty(struct merge_options *opt, const char *path)
866 {
867 struct cache_entry *ce;
868 int dirty = 1;
869
870 if (opt->priv->call_depth || !was_tracked(opt, path))
871 return !dirty;
872
873 ce = index_file_exists(opt->priv->unpack_opts.src_index,
874 path, strlen(path), ignore_case);
875 dirty = verify_uptodate(ce, &opt->priv->unpack_opts) != 0;
876 return dirty;
877 }
878
879 static int make_room_for_path(struct merge_options *opt, const char *path)
880 {
881 int status, i;
882 const char *msg = _("failed to create path '%s'%s");
883
884 /* Unlink any D/F conflict files that are in the way */
885 for (i = 0; i < opt->priv->df_conflict_file_set.nr; i++) {
886 const char *df_path = opt->priv->df_conflict_file_set.items[i].string;
887 size_t pathlen = strlen(path);
888 size_t df_pathlen = strlen(df_path);
889 if (df_pathlen < pathlen &&
890 path[df_pathlen] == '/' &&
891 strncmp(path, df_path, df_pathlen) == 0) {
892 output(opt, 3,
893 _("Removing %s to make room for subdirectory\n"),
894 df_path);
895 unlink(df_path);
896 unsorted_string_list_delete_item(&opt->priv->df_conflict_file_set,
897 i, 0);
898 break;
899 }
900 }
901
902 /* Make sure leading directories are created */
903 status = safe_create_leading_directories_const(path);
904 if (status) {
905 if (status == SCLD_EXISTS)
906 /* something else exists */
907 return err(opt, msg, path, _(": perhaps a D/F conflict?"));
908 return err(opt, msg, path, "");
909 }
910
911 /*
912 * Do not unlink a file in the work tree if we are not
913 * tracking it.
914 */
915 if (would_lose_untracked(opt, path))
916 return err(opt, _("refusing to lose untracked file at '%s'"),
917 path);
918
919 /* Successful unlink is good.. */
920 if (!unlink(path))
921 return 0;
922 /* .. and so is no existing file */
923 if (errno == ENOENT)
924 return 0;
925 /* .. but not some other error (who really cares what?) */
926 return err(opt, msg, path, _(": perhaps a D/F conflict?"));
927 }
928
929 static int update_file_flags(struct merge_options *opt,
930 const struct diff_filespec *contents,
931 const char *path,
932 int update_cache,
933 int update_wd)
934 {
935 int ret = 0;
936
937 if (opt->priv->call_depth)
938 update_wd = 0;
939
940 if (update_wd) {
941 enum object_type type;
942 void *buf;
943 unsigned long size;
944
945 if (S_ISGITLINK(contents->mode)) {
946 /*
947 * We may later decide to recursively descend into
948 * the submodule directory and update its index
949 * and/or work tree, but we do not do that now.
950 */
951 update_wd = 0;
952 goto update_index;
953 }
954
955 buf = read_object_file(&contents->oid, &type, &size);
956 if (!buf) {
957 ret = err(opt, _("cannot read object %s '%s'"),
958 oid_to_hex(&contents->oid), path);
959 goto free_buf;
960 }
961 if (type != OBJ_BLOB) {
962 ret = err(opt, _("blob expected for %s '%s'"),
963 oid_to_hex(&contents->oid), path);
964 goto free_buf;
965 }
966 if (S_ISREG(contents->mode)) {
967 struct strbuf strbuf = STRBUF_INIT;
968 if (convert_to_working_tree(opt->repo->index,
969 path, buf, size, &strbuf, NULL)) {
970 free(buf);
971 size = strbuf.len;
972 buf = strbuf_detach(&strbuf, NULL);
973 }
974 }
975
976 if (make_room_for_path(opt, path) < 0) {
977 update_wd = 0;
978 goto free_buf;
979 }
980 if (S_ISREG(contents->mode) ||
981 (!has_symlinks && S_ISLNK(contents->mode))) {
982 int fd;
983 int mode = (contents->mode & 0100 ? 0777 : 0666);
984
985 fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode);
986 if (fd < 0) {
987 ret = err(opt, _("failed to open '%s': %s"),
988 path, strerror(errno));
989 goto free_buf;
990 }
991 write_in_full(fd, buf, size);
992 close(fd);
993 } else if (S_ISLNK(contents->mode)) {
994 char *lnk = xmemdupz(buf, size);
995 safe_create_leading_directories_const(path);
996 unlink(path);
997 if (symlink(lnk, path))
998 ret = err(opt, _("failed to symlink '%s': %s"),
999 path, strerror(errno));
1000 free(lnk);
1001 } else
1002 ret = err(opt,
1003 _("do not know what to do with %06o %s '%s'"),
1004 contents->mode, oid_to_hex(&contents->oid), path);
1005 free_buf:
1006 free(buf);
1007 }
1008 update_index:
1009 if (!ret && update_cache) {
1010 int refresh = (!opt->priv->call_depth &&
1011 contents->mode != S_IFGITLINK);
1012 if (add_cacheinfo(opt, contents, path, 0, refresh,
1013 ADD_CACHE_OK_TO_ADD))
1014 return -1;
1015 }
1016 return ret;
1017 }
1018
1019 static int update_file(struct merge_options *opt,
1020 int clean,
1021 const struct diff_filespec *contents,
1022 const char *path)
1023 {
1024 return update_file_flags(opt, contents, path,
1025 opt->priv->call_depth || clean, !opt->priv->call_depth);
1026 }
1027
1028 /* Low level file merging, update and removal */
1029
1030 struct merge_file_info {
1031 struct diff_filespec blob; /* mostly use oid & mode; sometimes path */
1032 unsigned clean:1,
1033 merge:1;
1034 };
1035
1036 static int merge_3way(struct merge_options *opt,
1037 mmbuffer_t *result_buf,
1038 const struct diff_filespec *o,
1039 const struct diff_filespec *a,
1040 const struct diff_filespec *b,
1041 const char *branch1,
1042 const char *branch2,
1043 const int extra_marker_size)
1044 {
1045 mmfile_t orig, src1, src2;
1046 struct ll_merge_options ll_opts = {0};
1047 char *base, *name1, *name2;
1048 enum ll_merge_result merge_status;
1049
1050 ll_opts.renormalize = opt->renormalize;
1051 ll_opts.extra_marker_size = extra_marker_size;
1052 ll_opts.xdl_opts = opt->xdl_opts;
1053
1054 if (opt->priv->call_depth) {
1055 ll_opts.virtual_ancestor = 1;
1056 ll_opts.variant = 0;
1057 } else {
1058 switch (opt->recursive_variant) {
1059 case MERGE_VARIANT_OURS:
1060 ll_opts.variant = XDL_MERGE_FAVOR_OURS;
1061 break;
1062 case MERGE_VARIANT_THEIRS:
1063 ll_opts.variant = XDL_MERGE_FAVOR_THEIRS;
1064 break;
1065 default:
1066 ll_opts.variant = 0;
1067 break;
1068 }
1069 }
1070
1071 assert(a->path && b->path && o->path && opt->ancestor);
1072 if (strcmp(a->path, b->path) || strcmp(a->path, o->path) != 0) {
1073 base = mkpathdup("%s:%s", opt->ancestor, o->path);
1074 name1 = mkpathdup("%s:%s", branch1, a->path);
1075 name2 = mkpathdup("%s:%s", branch2, b->path);
1076 } else {
1077 base = mkpathdup("%s", opt->ancestor);
1078 name1 = mkpathdup("%s", branch1);
1079 name2 = mkpathdup("%s", branch2);
1080 }
1081
1082 read_mmblob(&orig, &o->oid);
1083 read_mmblob(&src1, &a->oid);
1084 read_mmblob(&src2, &b->oid);
1085
1086 /*
1087 * FIXME: Using a->path for normalization rules in ll_merge could be
1088 * wrong if we renamed from a->path to b->path. We should use the
1089 * target path for where the file will be written.
1090 */
1091 merge_status = ll_merge(result_buf, a->path, &orig, base,
1092 &src1, name1, &src2, name2,
1093 opt->repo->index, &ll_opts);
1094 if (merge_status == LL_MERGE_BINARY_CONFLICT)
1095 warning("Cannot merge binary files: %s (%s vs. %s)",
1096 a->path, name1, name2);
1097
1098 free(base);
1099 free(name1);
1100 free(name2);
1101 free(orig.ptr);
1102 free(src1.ptr);
1103 free(src2.ptr);
1104 return merge_status;
1105 }
1106
1107 static int find_first_merges(struct repository *repo,
1108 struct object_array *result, const char *path,
1109 struct commit *a, struct commit *b)
1110 {
1111 int i, j;
1112 struct object_array merges = OBJECT_ARRAY_INIT;
1113 struct commit *commit;
1114 int contains_another;
1115
1116 char merged_revision[GIT_MAX_HEXSZ + 2];
1117 const char *rev_args[] = { "rev-list", "--merges", "--ancestry-path",
1118 "--all", merged_revision, NULL };
1119 struct rev_info revs;
1120 struct setup_revision_opt rev_opts;
1121
1122 memset(result, 0, sizeof(struct object_array));
1123 memset(&rev_opts, 0, sizeof(rev_opts));
1124
1125 /* get all revisions that merge commit a */
1126 xsnprintf(merged_revision, sizeof(merged_revision), "^%s",
1127 oid_to_hex(&a->object.oid));
1128 repo_init_revisions(repo, &revs, NULL);
1129 /* FIXME: can't handle linked worktrees in submodules yet */
1130 revs.single_worktree = path != NULL;
1131 setup_revisions(ARRAY_SIZE(rev_args)-1, rev_args, &revs, &rev_opts);
1132
1133 /* save all revisions from the above list that contain b */
1134 if (prepare_revision_walk(&revs))
1135 die("revision walk setup failed");
1136 while ((commit = get_revision(&revs)) != NULL) {
1137 struct object *o = &(commit->object);
1138 if (repo_in_merge_bases(repo, b, commit))
1139 add_object_array(o, NULL, &merges);
1140 }
1141 reset_revision_walk();
1142
1143 /* Now we've got all merges that contain a and b. Prune all
1144 * merges that contain another found merge and save them in
1145 * result.
1146 */
1147 for (i = 0; i < merges.nr; i++) {
1148 struct commit *m1 = (struct commit *) merges.objects[i].item;
1149
1150 contains_another = 0;
1151 for (j = 0; j < merges.nr; j++) {
1152 struct commit *m2 = (struct commit *) merges.objects[j].item;
1153 if (i != j && repo_in_merge_bases(repo, m2, m1)) {
1154 contains_another = 1;
1155 break;
1156 }
1157 }
1158
1159 if (!contains_another)
1160 add_object_array(merges.objects[i].item, NULL, result);
1161 }
1162
1163 object_array_clear(&merges);
1164 release_revisions(&revs);
1165 return result->nr;
1166 }
1167
1168 static void print_commit(struct repository *repo, struct commit *commit)
1169 {
1170 struct strbuf sb = STRBUF_INIT;
1171 struct pretty_print_context ctx = {0};
1172 ctx.date_mode.type = DATE_NORMAL;
1173 /* FIXME: Merge this with output_commit_title() */
1174 assert(!merge_remote_util(commit));
1175 repo_format_commit_message(repo, commit, " %h: %m %s", &sb, &ctx);
1176 fprintf(stderr, "%s\n", sb.buf);
1177 strbuf_release(&sb);
1178 }
1179
1180 static int is_valid(const struct diff_filespec *dfs)
1181 {
1182 return dfs->mode != 0 && !is_null_oid(&dfs->oid);
1183 }
1184
1185 static int merge_submodule(struct merge_options *opt,
1186 struct object_id *result, const char *path,
1187 const struct object_id *base, const struct object_id *a,
1188 const struct object_id *b)
1189 {
1190 struct repository subrepo;
1191 int ret = 0;
1192 struct commit *commit_base, *commit_a, *commit_b;
1193 int parent_count;
1194 struct object_array merges;
1195
1196 int i;
1197 int search = !opt->priv->call_depth;
1198
1199 /* store a in result in case we fail */
1200 /* FIXME: This is the WRONG resolution for the recursive case when
1201 * we need to be careful to avoid accidentally matching either side.
1202 * Should probably use o instead there, much like we do for merging
1203 * binaries.
1204 */
1205 oidcpy(result, a);
1206
1207 /* we can not handle deletion conflicts */
1208 if (is_null_oid(base))
1209 return 0;
1210 if (is_null_oid(a))
1211 return 0;
1212 if (is_null_oid(b))
1213 return 0;
1214
1215 if (repo_submodule_init(&subrepo, opt->repo, path, null_oid())) {
1216 output(opt, 1, _("Failed to merge submodule %s (not checked out)"), path);
1217 return 0;
1218 }
1219
1220 if (!(commit_base = lookup_commit_reference(&subrepo, base)) ||
1221 !(commit_a = lookup_commit_reference(&subrepo, a)) ||
1222 !(commit_b = lookup_commit_reference(&subrepo, b))) {
1223 output(opt, 1, _("Failed to merge submodule %s (commits not present)"), path);
1224 goto cleanup;
1225 }
1226
1227 /* check whether both changes are forward */
1228 if (!repo_in_merge_bases(&subrepo, commit_base, commit_a) ||
1229 !repo_in_merge_bases(&subrepo, commit_base, commit_b)) {
1230 output(opt, 1, _("Failed to merge submodule %s (commits don't follow merge-base)"), path);
1231 goto cleanup;
1232 }
1233
1234 /* Case #1: a is contained in b or vice versa */
1235 if (repo_in_merge_bases(&subrepo, commit_a, commit_b)) {
1236 oidcpy(result, b);
1237 if (show(opt, 3)) {
1238 output(opt, 3, _("Fast-forwarding submodule %s to the following commit:"), path);
1239 repo_output_commit_title(opt, &subrepo, commit_b);
1240 } else if (show(opt, 2))
1241 output(opt, 2, _("Fast-forwarding submodule %s"), path);
1242 else
1243 ; /* no output */
1244
1245 ret = 1;
1246 goto cleanup;
1247 }
1248 if (repo_in_merge_bases(&subrepo, commit_b, commit_a)) {
1249 oidcpy(result, a);
1250 if (show(opt, 3)) {
1251 output(opt, 3, _("Fast-forwarding submodule %s to the following commit:"), path);
1252 repo_output_commit_title(opt, &subrepo, commit_a);
1253 } else if (show(opt, 2))
1254 output(opt, 2, _("Fast-forwarding submodule %s"), path);
1255 else
1256 ; /* no output */
1257
1258 ret = 1;
1259 goto cleanup;
1260 }
1261
1262 /*
1263 * Case #2: There are one or more merges that contain a and b in
1264 * the submodule. If there is only one, then present it as a
1265 * suggestion to the user, but leave it marked unmerged so the
1266 * user needs to confirm the resolution.
1267 */
1268
1269 /* Skip the search if makes no sense to the calling context. */
1270 if (!search)
1271 goto cleanup;
1272
1273 /* find commit which merges them */
1274 parent_count = find_first_merges(&subrepo, &merges, path,
1275 commit_a, commit_b);
1276 switch (parent_count) {
1277 case 0:
1278 output(opt, 1, _("Failed to merge submodule %s (merge following commits not found)"), path);
1279 break;
1280
1281 case 1:
1282 output(opt, 1, _("Failed to merge submodule %s (not fast-forward)"), path);
1283 output(opt, 2, _("Found a possible merge resolution for the submodule:\n"));
1284 print_commit(&subrepo, (struct commit *) merges.objects[0].item);
1285 output(opt, 2, _(
1286 "If this is correct simply add it to the index "
1287 "for example\n"
1288 "by using:\n\n"
1289 " git update-index --cacheinfo 160000 %s \"%s\"\n\n"
1290 "which will accept this suggestion.\n"),
1291 oid_to_hex(&merges.objects[0].item->oid), path);
1292 break;
1293
1294 default:
1295 output(opt, 1, _("Failed to merge submodule %s (multiple merges found)"), path);
1296 for (i = 0; i < merges.nr; i++)
1297 print_commit(&subrepo, (struct commit *) merges.objects[i].item);
1298 }
1299
1300 object_array_clear(&merges);
1301 cleanup:
1302 repo_clear(&subrepo);
1303 return ret;
1304 }
1305
1306 static int merge_mode_and_contents(struct merge_options *opt,
1307 const struct diff_filespec *o,
1308 const struct diff_filespec *a,
1309 const struct diff_filespec *b,
1310 const char *filename,
1311 const char *branch1,
1312 const char *branch2,
1313 const int extra_marker_size,
1314 struct merge_file_info *result)
1315 {
1316 if (opt->branch1 != branch1) {
1317 /*
1318 * It's weird getting a reverse merge with HEAD on the bottom
1319 * side of the conflict markers and the other branch on the
1320 * top. Fix that.
1321 */
1322 return merge_mode_and_contents(opt, o, b, a,
1323 filename,
1324 branch2, branch1,
1325 extra_marker_size, result);
1326 }
1327
1328 result->merge = 0;
1329 result->clean = 1;
1330
1331 if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) {
1332 result->clean = 0;
1333 /*
1334 * FIXME: This is a bad resolution for recursive case; for
1335 * the recursive case we want something that is unlikely to
1336 * accidentally match either side. Also, while it makes
1337 * sense to prefer regular files over symlinks, it doesn't
1338 * make sense to prefer regular files over submodules.
1339 */
1340 if (S_ISREG(a->mode)) {
1341 result->blob.mode = a->mode;
1342 oidcpy(&result->blob.oid, &a->oid);
1343 } else {
1344 result->blob.mode = b->mode;
1345 oidcpy(&result->blob.oid, &b->oid);
1346 }
1347 } else {
1348 if (!oideq(&a->oid, &o->oid) && !oideq(&b->oid, &o->oid))
1349 result->merge = 1;
1350
1351 /*
1352 * Merge modes
1353 */
1354 if (a->mode == b->mode || a->mode == o->mode)
1355 result->blob.mode = b->mode;
1356 else {
1357 result->blob.mode = a->mode;
1358 if (b->mode != o->mode) {
1359 result->clean = 0;
1360 result->merge = 1;
1361 }
1362 }
1363
1364 if (oideq(&a->oid, &b->oid) || oideq(&a->oid, &o->oid))
1365 oidcpy(&result->blob.oid, &b->oid);
1366 else if (oideq(&b->oid, &o->oid))
1367 oidcpy(&result->blob.oid, &a->oid);
1368 else if (S_ISREG(a->mode)) {
1369 mmbuffer_t result_buf;
1370 int ret = 0, merge_status;
1371
1372 merge_status = merge_3way(opt, &result_buf, o, a, b,
1373 branch1, branch2,
1374 extra_marker_size);
1375
1376 if ((merge_status < 0) || !result_buf.ptr)
1377 ret = err(opt, _("Failed to execute internal merge"));
1378
1379 if (!ret &&
1380 write_object_file(result_buf.ptr, result_buf.size,
1381 OBJ_BLOB, &result->blob.oid))
1382 ret = err(opt, _("Unable to add %s to database"),
1383 a->path);
1384
1385 free(result_buf.ptr);
1386 if (ret)
1387 return ret;
1388 /* FIXME: bug, what if modes didn't match? */
1389 result->clean = (merge_status == 0);
1390 } else if (S_ISGITLINK(a->mode)) {
1391 result->clean = merge_submodule(opt, &result->blob.oid,
1392 o->path,
1393 &o->oid,
1394 &a->oid,
1395 &b->oid);
1396 } else if (S_ISLNK(a->mode)) {
1397 switch (opt->recursive_variant) {
1398 case MERGE_VARIANT_NORMAL:
1399 oidcpy(&result->blob.oid, &a->oid);
1400 if (!oideq(&a->oid, &b->oid))
1401 result->clean = 0;
1402 break;
1403 case MERGE_VARIANT_OURS:
1404 oidcpy(&result->blob.oid, &a->oid);
1405 break;
1406 case MERGE_VARIANT_THEIRS:
1407 oidcpy(&result->blob.oid, &b->oid);
1408 break;
1409 }
1410 } else
1411 BUG("unsupported object type in the tree");
1412 }
1413
1414 if (result->merge)
1415 output(opt, 2, _("Auto-merging %s"), filename);
1416
1417 return 0;
1418 }
1419
1420 static int handle_rename_via_dir(struct merge_options *opt,
1421 struct rename_conflict_info *ci)
1422 {
1423 /*
1424 * Handle file adds that need to be renamed due to directory rename
1425 * detection. This differs from handle_rename_normal, because
1426 * there is no content merge to do; just move the file into the
1427 * desired final location.
1428 */
1429 const struct rename *ren = ci->ren1;
1430 const struct diff_filespec *dest = ren->pair->two;
1431 char *file_path = dest->path;
1432 int mark_conflicted = (opt->detect_directory_renames ==
1433 MERGE_DIRECTORY_RENAMES_CONFLICT);
1434 assert(ren->dir_rename_original_dest);
1435
1436 if (!opt->priv->call_depth && would_lose_untracked(opt, dest->path)) {
1437 mark_conflicted = 1;
1438 file_path = unique_path(opt, dest->path, ren->branch);
1439 output(opt, 1, _("Error: Refusing to lose untracked file at %s; "
1440 "writing to %s instead."),
1441 dest->path, file_path);
1442 }
1443
1444 if (mark_conflicted) {
1445 /*
1446 * Write the file in worktree at file_path. In the index,
1447 * only record the file at dest->path in the appropriate
1448 * higher stage.
1449 */
1450 if (update_file(opt, 0, dest, file_path))
1451 return -1;
1452 if (file_path != dest->path)
1453 free(file_path);
1454 if (update_stages(opt, dest->path, NULL,
1455 ren->branch == opt->branch1 ? dest : NULL,
1456 ren->branch == opt->branch1 ? NULL : dest))
1457 return -1;
1458 return 0; /* not clean, but conflicted */
1459 } else {
1460 /* Update dest->path both in index and in worktree */
1461 if (update_file(opt, 1, dest, dest->path))
1462 return -1;
1463 return 1; /* clean */
1464 }
1465 }
1466
1467 static int handle_change_delete(struct merge_options *opt,
1468 const char *path, const char *old_path,
1469 const struct diff_filespec *o,
1470 const struct diff_filespec *changed,
1471 const char *change_branch,
1472 const char *delete_branch,
1473 const char *change, const char *change_past)
1474 {
1475 char *alt_path = NULL;
1476 const char *update_path = path;
1477 int ret = 0;
1478
1479 if (dir_in_way(opt->repo->index, path, !opt->priv->call_depth, 0) ||
1480 (!opt->priv->call_depth && would_lose_untracked(opt, path))) {
1481 update_path = alt_path = unique_path(opt, path, change_branch);
1482 }
1483
1484 if (opt->priv->call_depth) {
1485 /*
1486 * We cannot arbitrarily accept either a_sha or b_sha as
1487 * correct; since there is no true "middle point" between
1488 * them, simply reuse the base version for virtual merge base.
1489 */
1490 ret = remove_file_from_index(opt->repo->index, path);
1491 if (!ret)
1492 ret = update_file(opt, 0, o, update_path);
1493 } else {
1494 /*
1495 * Despite the four nearly duplicate messages and argument
1496 * lists below and the ugliness of the nested if-statements,
1497 * having complete messages makes the job easier for
1498 * translators.
1499 *
1500 * The slight variance among the cases is due to the fact
1501 * that:
1502 * 1) directory/file conflicts (in effect if
1503 * !alt_path) could cause us to need to write the
1504 * file to a different path.
1505 * 2) renames (in effect if !old_path) could mean that
1506 * there are two names for the path that the user
1507 * may know the file by.
1508 */
1509 if (!alt_path) {
1510 if (!old_path) {
1511 output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1512 "and %s in %s. Version %s of %s left in tree."),
1513 change, path, delete_branch, change_past,
1514 change_branch, change_branch, path);
1515 } else {
1516 output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1517 "and %s to %s in %s. Version %s of %s left in tree."),
1518 change, old_path, delete_branch, change_past, path,
1519 change_branch, change_branch, path);
1520 }
1521 } else {
1522 if (!old_path) {
1523 output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1524 "and %s in %s. Version %s of %s left in tree at %s."),
1525 change, path, delete_branch, change_past,
1526 change_branch, change_branch, path, alt_path);
1527 } else {
1528 output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1529 "and %s to %s in %s. Version %s of %s left in tree at %s."),
1530 change, old_path, delete_branch, change_past, path,
1531 change_branch, change_branch, path, alt_path);
1532 }
1533 }
1534 /*
1535 * No need to call update_file() on path when change_branch ==
1536 * opt->branch1 && !alt_path, since that would needlessly touch
1537 * path. We could call update_file_flags() with update_cache=0
1538 * and update_wd=0, but that's a no-op.
1539 */
1540 if (change_branch != opt->branch1 || alt_path)
1541 ret = update_file(opt, 0, changed, update_path);
1542 }
1543 free(alt_path);
1544
1545 return ret;
1546 }
1547
1548 static int handle_rename_delete(struct merge_options *opt,
1549 struct rename_conflict_info *ci)
1550 {
1551 const struct rename *ren = ci->ren1;
1552 const struct diff_filespec *orig = ren->pair->one;
1553 const struct diff_filespec *dest = ren->pair->two;
1554 const char *rename_branch = ren->branch;
1555 const char *delete_branch = (opt->branch1 == ren->branch ?
1556 opt->branch2 : opt->branch1);
1557
1558 if (handle_change_delete(opt,
1559 opt->priv->call_depth ? orig->path : dest->path,
1560 opt->priv->call_depth ? NULL : orig->path,
1561 orig, dest,
1562 rename_branch, delete_branch,
1563 _("rename"), _("renamed")))
1564 return -1;
1565
1566 if (opt->priv->call_depth)
1567 return remove_file_from_index(opt->repo->index, dest->path);
1568 else
1569 return update_stages(opt, dest->path, NULL,
1570 rename_branch == opt->branch1 ? dest : NULL,
1571 rename_branch == opt->branch1 ? NULL : dest);
1572 }
1573
1574 static int handle_file_collision(struct merge_options *opt,
1575 const char *collide_path,
1576 const char *prev_path1,
1577 const char *prev_path2,
1578 const char *branch1, const char *branch2,
1579 struct diff_filespec *a,
1580 struct diff_filespec *b)
1581 {
1582 struct merge_file_info mfi;
1583 struct diff_filespec null;
1584 char *alt_path = NULL;
1585 const char *update_path = collide_path;
1586
1587 /*
1588 * It's easiest to get the correct things into stage 2 and 3, and
1589 * to make sure that the content merge puts HEAD before the other
1590 * branch if we just ensure that branch1 == opt->branch1. So, simply
1591 * flip arguments around if we don't have that.
1592 */
1593 if (branch1 != opt->branch1) {
1594 return handle_file_collision(opt, collide_path,
1595 prev_path2, prev_path1,
1596 branch2, branch1,
1597 b, a);
1598 }
1599
1600 /* Remove rename sources if rename/add or rename/rename(2to1) */
1601 if (prev_path1)
1602 remove_file(opt, 1, prev_path1,
1603 opt->priv->call_depth || would_lose_untracked(opt, prev_path1));
1604 if (prev_path2)
1605 remove_file(opt, 1, prev_path2,
1606 opt->priv->call_depth || would_lose_untracked(opt, prev_path2));
1607
1608 /*
1609 * Remove the collision path, if it wouldn't cause dirty contents
1610 * or an untracked file to get lost. We'll either overwrite with
1611 * merged contents, or just write out to differently named files.
1612 */
1613 if (was_dirty(opt, collide_path)) {
1614 output(opt, 1, _("Refusing to lose dirty file at %s"),
1615 collide_path);
1616 update_path = alt_path = unique_path(opt, collide_path, "merged");
1617 } else if (would_lose_untracked(opt, collide_path)) {
1618 /*
1619 * Only way we get here is if both renames were from
1620 * a directory rename AND user had an untracked file
1621 * at the location where both files end up after the
1622 * two directory renames. See testcase 10d of t6043.
1623 */
1624 output(opt, 1, _("Refusing to lose untracked file at "
1625 "%s, even though it's in the way."),
1626 collide_path);
1627 update_path = alt_path = unique_path(opt, collide_path, "merged");
1628 } else {
1629 /*
1630 * FIXME: It's possible that the two files are identical
1631 * and that the current working copy happens to match, in
1632 * which case we are unnecessarily touching the working
1633 * tree file. It's not a likely enough scenario that I
1634 * want to code up the checks for it and a better fix is
1635 * available if we restructure how unpack_trees() and
1636 * merge-recursive interoperate anyway, so punting for
1637 * now...
1638 */
1639 remove_file(opt, 0, collide_path, 0);
1640 }
1641
1642 /* Store things in diff_filespecs for functions that need it */
1643 null.path = (char *)collide_path;
1644 oidcpy(&null.oid, null_oid());
1645 null.mode = 0;
1646
1647 if (merge_mode_and_contents(opt, &null, a, b, collide_path,
1648 branch1, branch2, opt->priv->call_depth * 2, &mfi))
1649 return -1;
1650 mfi.clean &= !alt_path;
1651 if (update_file(opt, mfi.clean, &mfi.blob, update_path))
1652 return -1;
1653 if (!mfi.clean && !opt->priv->call_depth &&
1654 update_stages(opt, collide_path, NULL, a, b))
1655 return -1;
1656 free(alt_path);
1657 /*
1658 * FIXME: If both a & b both started with conflicts (only possible
1659 * if they came from a rename/rename(2to1)), but had IDENTICAL
1660 * contents including those conflicts, then in the next line we claim
1661 * it was clean. If someone cares about this case, we should have the
1662 * caller notify us if we started with conflicts.
1663 */
1664 return mfi.clean;
1665 }
1666
1667 static int handle_rename_add(struct merge_options *opt,
1668 struct rename_conflict_info *ci)
1669 {
1670 /* a was renamed to c, and a separate c was added. */
1671 struct diff_filespec *a = ci->ren1->pair->one;
1672 struct diff_filespec *c = ci->ren1->pair->two;
1673 char *path = c->path;
1674 char *prev_path_desc;
1675 struct merge_file_info mfi;
1676
1677 const char *rename_branch = ci->ren1->branch;
1678 const char *add_branch = (opt->branch1 == rename_branch ?
1679 opt->branch2 : opt->branch1);
1680 int other_stage = (ci->ren1->branch == opt->branch1 ? 3 : 2);
1681
1682 output(opt, 1, _("CONFLICT (rename/add): "
1683 "Rename %s->%s in %s. Added %s in %s"),
1684 a->path, c->path, rename_branch,
1685 c->path, add_branch);
1686
1687 prev_path_desc = xstrfmt("version of %s from %s", path, a->path);
1688 ci->ren1->src_entry->stages[other_stage].path = a->path;
1689 if (merge_mode_and_contents(opt, a, c,
1690 &ci->ren1->src_entry->stages[other_stage],
1691 prev_path_desc,
1692 opt->branch1, opt->branch2,
1693 1 + opt->priv->call_depth * 2, &mfi))
1694 return -1;
1695 free(prev_path_desc);
1696
1697 ci->ren1->dst_entry->stages[other_stage].path = mfi.blob.path = c->path;
1698 return handle_file_collision(opt,
1699 c->path, a->path, NULL,
1700 rename_branch, add_branch,
1701 &mfi.blob,
1702 &ci->ren1->dst_entry->stages[other_stage]);
1703 }
1704
1705 static char *find_path_for_conflict(struct merge_options *opt,
1706 const char *path,
1707 const char *branch1,
1708 const char *branch2)
1709 {
1710 char *new_path = NULL;
1711 if (dir_in_way(opt->repo->index, path, !opt->priv->call_depth, 0)) {
1712 new_path = unique_path(opt, path, branch1);
1713 output(opt, 1, _("%s is a directory in %s adding "
1714 "as %s instead"),
1715 path, branch2, new_path);
1716 } else if (would_lose_untracked(opt, path)) {
1717 new_path = unique_path(opt, path, branch1);
1718 output(opt, 1, _("Refusing to lose untracked file"
1719 " at %s; adding as %s instead"),
1720 path, new_path);
1721 }
1722
1723 return new_path;
1724 }
1725
1726 /*
1727 * Toggle the stage number between "ours" and "theirs" (2 and 3).
1728 */
1729 static inline int flip_stage(int stage)
1730 {
1731 return (2 + 3) - stage;
1732 }
1733
1734 static int handle_rename_rename_1to2(struct merge_options *opt,
1735 struct rename_conflict_info *ci)
1736 {
1737 /* One file was renamed in both branches, but to different names. */
1738 struct merge_file_info mfi;
1739 struct diff_filespec *add;
1740 struct diff_filespec *o = ci->ren1->pair->one;
1741 struct diff_filespec *a = ci->ren1->pair->two;
1742 struct diff_filespec *b = ci->ren2->pair->two;
1743 char *path_desc;
1744
1745 output(opt, 1, _("CONFLICT (rename/rename): "
1746 "Rename \"%s\"->\"%s\" in branch \"%s\" "
1747 "rename \"%s\"->\"%s\" in \"%s\"%s"),
1748 o->path, a->path, ci->ren1->branch,
1749 o->path, b->path, ci->ren2->branch,
1750 opt->priv->call_depth ? _(" (left unresolved)") : "");
1751
1752 path_desc = xstrfmt("%s and %s, both renamed from %s",
1753 a->path, b->path, o->path);
1754 if (merge_mode_and_contents(opt, o, a, b, path_desc,
1755 ci->ren1->branch, ci->ren2->branch,
1756 opt->priv->call_depth * 2, &mfi))
1757 return -1;
1758 free(path_desc);
1759
1760 if (opt->priv->call_depth)
1761 remove_file_from_index(opt->repo->index, o->path);
1762
1763 /*
1764 * For each destination path, we need to see if there is a
1765 * rename/add collision. If not, we can write the file out
1766 * to the specified location.
1767 */
1768 add = &ci->ren1->dst_entry->stages[flip_stage(2)];
1769 if (is_valid(add)) {
1770 add->path = mfi.blob.path = a->path;
1771 if (handle_file_collision(opt, a->path,
1772 NULL, NULL,
1773 ci->ren1->branch,
1774 ci->ren2->branch,
1775 &mfi.blob, add) < 0)
1776 return -1;
1777 } else {
1778 char *new_path = find_path_for_conflict(opt, a->path,
1779 ci->ren1->branch,
1780 ci->ren2->branch);
1781 if (update_file(opt, 0, &mfi.blob,
1782 new_path ? new_path : a->path))
1783 return -1;
1784 free(new_path);
1785 if (!opt->priv->call_depth &&
1786 update_stages(opt, a->path, NULL, a, NULL))
1787 return -1;
1788 }
1789
1790 if (!mfi.clean && mfi.blob.mode == a->mode &&
1791 oideq(&mfi.blob.oid, &a->oid)) {
1792 /*
1793 * Getting here means we were attempting to merge a binary
1794 * blob. Since we can't merge binaries, the merge algorithm
1795 * just takes one side. But we don't want to copy the
1796 * contents of one side to both paths; we'd rather use the
1797 * original content at the given path for each path.
1798 */
1799 oidcpy(&mfi.blob.oid, &b->oid);
1800 mfi.blob.mode = b->mode;
1801 }
1802 add = &ci->ren2->dst_entry->stages[flip_stage(3)];
1803 if (is_valid(add)) {
1804 add->path = mfi.blob.path = b->path;
1805 if (handle_file_collision(opt, b->path,
1806 NULL, NULL,
1807 ci->ren1->branch,
1808 ci->ren2->branch,
1809 add, &mfi.blob) < 0)
1810 return -1;
1811 } else {
1812 char *new_path = find_path_for_conflict(opt, b->path,
1813 ci->ren2->branch,
1814 ci->ren1->branch);
1815 if (update_file(opt, 0, &mfi.blob,
1816 new_path ? new_path : b->path))
1817 return -1;
1818 free(new_path);
1819 if (!opt->priv->call_depth &&
1820 update_stages(opt, b->path, NULL, NULL, b))
1821 return -1;
1822 }
1823
1824 return 0;
1825 }
1826
1827 static int handle_rename_rename_2to1(struct merge_options *opt,
1828 struct rename_conflict_info *ci)
1829 {
1830 /* Two files, a & b, were renamed to the same thing, c. */
1831 struct diff_filespec *a = ci->ren1->pair->one;
1832 struct diff_filespec *b = ci->ren2->pair->one;
1833 struct diff_filespec *c1 = ci->ren1->pair->two;
1834 struct diff_filespec *c2 = ci->ren2->pair->two;
1835 char *path = c1->path; /* == c2->path */
1836 char *path_side_1_desc;
1837 char *path_side_2_desc;
1838 struct merge_file_info mfi_c1;
1839 struct merge_file_info mfi_c2;
1840 int ostage1, ostage2;
1841
1842 output(opt, 1, _("CONFLICT (rename/rename): "
1843 "Rename %s->%s in %s. "
1844 "Rename %s->%s in %s"),
1845 a->path, c1->path, ci->ren1->branch,
1846 b->path, c2->path, ci->ren2->branch);
1847
1848 path_side_1_desc = xstrfmt("version of %s from %s", path, a->path);
1849 path_side_2_desc = xstrfmt("version of %s from %s", path, b->path);
1850 ostage1 = ci->ren1->branch == opt->branch1 ? 3 : 2;
1851 ostage2 = flip_stage(ostage1);
1852 ci->ren1->src_entry->stages[ostage1].path = a->path;
1853 ci->ren2->src_entry->stages[ostage2].path = b->path;
1854 if (merge_mode_and_contents(opt, a, c1,
1855 &ci->ren1->src_entry->stages[ostage1],
1856 path_side_1_desc,
1857 opt->branch1, opt->branch2,
1858 1 + opt->priv->call_depth * 2, &mfi_c1) ||
1859 merge_mode_and_contents(opt, b,
1860 &ci->ren2->src_entry->stages[ostage2],
1861 c2, path_side_2_desc,
1862 opt->branch1, opt->branch2,
1863 1 + opt->priv->call_depth * 2, &mfi_c2))
1864 return -1;
1865 free(path_side_1_desc);
1866 free(path_side_2_desc);
1867 mfi_c1.blob.path = path;
1868 mfi_c2.blob.path = path;
1869
1870 return handle_file_collision(opt, path, a->path, b->path,
1871 ci->ren1->branch, ci->ren2->branch,
1872 &mfi_c1.blob, &mfi_c2.blob);
1873 }
1874
1875 /*
1876 * Get the diff_filepairs changed between o_tree and tree.
1877 */
1878 static struct diff_queue_struct *get_diffpairs(struct merge_options *opt,
1879 struct tree *o_tree,
1880 struct tree *tree)
1881 {
1882 struct diff_queue_struct *ret;
1883 struct diff_options opts;
1884
1885 repo_diff_setup(opt->repo, &opts);
1886 opts.flags.recursive = 1;
1887 opts.flags.rename_empty = 0;
1888 opts.detect_rename = merge_detect_rename(opt);
1889 /*
1890 * We do not have logic to handle the detection of copies. In
1891 * fact, it may not even make sense to add such logic: would we
1892 * really want a change to a base file to be propagated through
1893 * multiple other files by a merge?
1894 */
1895 if (opts.detect_rename > DIFF_DETECT_RENAME)
1896 opts.detect_rename = DIFF_DETECT_RENAME;
1897 opts.rename_limit = (opt->rename_limit >= 0) ? opt->rename_limit : 7000;
1898 opts.rename_score = opt->rename_score;
1899 opts.show_rename_progress = opt->show_rename_progress;
1900 opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1901 diff_setup_done(&opts);
1902 diff_tree_oid(&o_tree->object.oid, &tree->object.oid, "", &opts);
1903 diffcore_std(&opts);
1904 if (opts.needed_rename_limit > opt->priv->needed_rename_limit)
1905 opt->priv->needed_rename_limit = opts.needed_rename_limit;
1906
1907 ret = xmalloc(sizeof(*ret));
1908 *ret = diff_queued_diff;
1909
1910 opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1911 diff_queued_diff.nr = 0;
1912 diff_queued_diff.queue = NULL;
1913 diff_flush(&opts);
1914 return ret;
1915 }
1916
1917 static int tree_has_path(struct repository *r, struct tree *tree,
1918 const char *path)
1919 {
1920 struct object_id hashy;
1921 unsigned short mode_o;
1922
1923 return !get_tree_entry(r,
1924 &tree->object.oid, path,
1925 &hashy, &mode_o);
1926 }
1927
1928 /*
1929 * Return a new string that replaces the beginning portion (which matches
1930 * entry->dir), with entry->new_dir. In perl-speak:
1931 * new_path_name = (old_path =~ s/entry->dir/entry->new_dir/);
1932 * NOTE:
1933 * Caller must ensure that old_path starts with entry->dir + '/'.
1934 */
1935 static char *apply_dir_rename(struct dir_rename_entry *entry,
1936 const char *old_path)
1937 {
1938 struct strbuf new_path = STRBUF_INIT;
1939 int oldlen, newlen;
1940
1941 if (entry->non_unique_new_dir)
1942 return NULL;
1943
1944 oldlen = strlen(entry->dir);
1945 if (entry->new_dir.len == 0)
1946 /*
1947 * If someone renamed/merged a subdirectory into the root
1948 * directory (e.g. 'some/subdir' -> ''), then we want to
1949 * avoid returning
1950 * '' + '/filename'
1951 * as the rename; we need to make old_path + oldlen advance
1952 * past the '/' character.
1953 */
1954 oldlen++;
1955 newlen = entry->new_dir.len + (strlen(old_path) - oldlen) + 1;
1956 strbuf_grow(&new_path, newlen);
1957 strbuf_addbuf(&new_path, &entry->new_dir);
1958 strbuf_addstr(&new_path, &old_path[oldlen]);
1959
1960 return strbuf_detach(&new_path, NULL);
1961 }
1962
1963 static void get_renamed_dir_portion(const char *old_path, const char *new_path,
1964 char **old_dir, char **new_dir)
1965 {
1966 char *end_of_old, *end_of_new;
1967
1968 /* Default return values: NULL, meaning no rename */
1969 *old_dir = NULL;
1970 *new_dir = NULL;
1971
1972 /*
1973 * For
1974 * "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"
1975 * the "e/foo.c" part is the same, we just want to know that
1976 * "a/b/c/d" was renamed to "a/b/some/thing/else"
1977 * so, for this example, this function returns "a/b/c/d" in
1978 * *old_dir and "a/b/some/thing/else" in *new_dir.
1979 */
1980
1981 /*
1982 * If the basename of the file changed, we don't care. We want
1983 * to know which portion of the directory, if any, changed.
1984 */
1985 end_of_old = strrchr(old_path, '/');
1986 end_of_new = strrchr(new_path, '/');
1987
1988 /*
1989 * If end_of_old is NULL, old_path wasn't in a directory, so there
1990 * could not be a directory rename (our rule elsewhere that a
1991 * directory which still exists is not considered to have been
1992 * renamed means the root directory can never be renamed -- because
1993 * the root directory always exists).
1994 */
1995 if (!end_of_old)
1996 return; /* Note: *old_dir and *new_dir are still NULL */
1997
1998 /*
1999 * If new_path contains no directory (end_of_new is NULL), then we
2000 * have a rename of old_path's directory to the root directory.
2001 */
2002 if (!end_of_new) {
2003 *old_dir = xstrndup(old_path, end_of_old - old_path);
2004 *new_dir = xstrdup("");
2005 return;
2006 }
2007
2008 /* Find the first non-matching character traversing backwards */
2009 while (*--end_of_new == *--end_of_old &&
2010 end_of_old != old_path &&
2011 end_of_new != new_path)
2012 ; /* Do nothing; all in the while loop */
2013
2014 /*
2015 * If both got back to the beginning of their strings, then the
2016 * directory didn't change at all, only the basename did.
2017 */
2018 if (end_of_old == old_path && end_of_new == new_path &&
2019 *end_of_old == *end_of_new)
2020 return; /* Note: *old_dir and *new_dir are still NULL */
2021
2022 /*
2023 * If end_of_new got back to the beginning of its string, and
2024 * end_of_old got back to the beginning of some subdirectory, then
2025 * we have a rename/merge of a subdirectory into the root, which
2026 * needs slightly special handling.
2027 *
2028 * Note: There is no need to consider the opposite case, with a
2029 * rename/merge of the root directory into some subdirectory
2030 * because as noted above the root directory always exists so it
2031 * cannot be considered to be renamed.
2032 */
2033 if (end_of_new == new_path &&
2034 end_of_old != old_path && end_of_old[-1] == '/') {
2035 *old_dir = xstrndup(old_path, --end_of_old - old_path);
2036 *new_dir = xstrdup("");
2037 return;
2038 }
2039
2040 /*
2041 * We've found the first non-matching character in the directory
2042 * paths. That means the current characters we were looking at
2043 * were part of the first non-matching subdir name going back from
2044 * the end of the strings. Get the whole name by advancing both
2045 * end_of_old and end_of_new to the NEXT '/' character. That will
2046 * represent the entire directory rename.
2047 *
2048 * The reason for the increment is cases like
2049 * a/b/star/foo/whatever.c -> a/b/tar/foo/random.c
2050 * After dropping the basename and going back to the first
2051 * non-matching character, we're now comparing:
2052 * a/b/s and a/b/
2053 * and we want to be comparing:
2054 * a/b/star/ and a/b/tar/
2055 * but without the pre-increment, the one on the right would stay
2056 * a/b/.
2057 */
2058 end_of_old = strchr(++end_of_old, '/');
2059 end_of_new = strchr(++end_of_new, '/');
2060
2061 /* Copy the old and new directories into *old_dir and *new_dir. */
2062 *old_dir = xstrndup(old_path, end_of_old - old_path);
2063 *new_dir = xstrndup(new_path, end_of_new - new_path);
2064 }
2065
2066 static void remove_hashmap_entries(struct hashmap *dir_renames,
2067 struct string_list *items_to_remove)
2068 {
2069 int i;
2070 struct dir_rename_entry *entry;
2071
2072 for (i = 0; i < items_to_remove->nr; i++) {
2073 entry = items_to_remove->items[i].util;
2074 hashmap_remove(dir_renames, &entry->ent, NULL);
2075 }
2076 string_list_clear(items_to_remove, 0);
2077 }
2078
2079 /*
2080 * See if there is a directory rename for path, and if there are any file
2081 * level conflicts for the renamed location. If there is a rename and
2082 * there are no conflicts, return the new name. Otherwise, return NULL.
2083 */
2084 static char *handle_path_level_conflicts(struct merge_options *opt,
2085 const char *path,
2086 struct dir_rename_entry *entry,
2087 struct hashmap *collisions,
2088 struct tree *tree)
2089 {
2090 char *new_path = NULL;
2091 struct collision_entry *collision_ent;
2092 int clean = 1;
2093 struct strbuf collision_paths = STRBUF_INIT;
2094
2095 /*
2096 * entry has the mapping of old directory name to new directory name
2097 * that we want to apply to path.
2098 */
2099 new_path = apply_dir_rename(entry, path);
2100
2101 if (!new_path) {
2102 /* This should only happen when entry->non_unique_new_dir set */
2103 if (!entry->non_unique_new_dir)
2104 BUG("entry->non_unique_new_dir not set and !new_path");
2105 output(opt, 1, _("CONFLICT (directory rename split): "
2106 "Unclear where to place %s because directory "
2107 "%s was renamed to multiple other directories, "
2108 "with no destination getting a majority of the "
2109 "files."),
2110 path, entry->dir);
2111 clean = 0;
2112 return NULL;
2113 }
2114
2115 /*
2116 * The caller needs to have ensured that it has pre-populated
2117 * collisions with all paths that map to new_path. Do a quick check
2118 * to ensure that's the case.
2119 */
2120 collision_ent = collision_find_entry(collisions, new_path);
2121 if (!collision_ent)
2122 BUG("collision_ent is NULL");
2123
2124 /*
2125 * Check for one-sided add/add/.../add conflicts, i.e.
2126 * where implicit renames from the other side doing
2127 * directory rename(s) can affect this side of history
2128 * to put multiple paths into the same location. Warn
2129 * and bail on directory renames for such paths.
2130 */
2131 if (collision_ent->reported_already) {
2132 clean = 0;
2133 } else if (tree_has_path(opt->repo, tree, new_path)) {
2134 collision_ent->reported_already = 1;
2135 strbuf_add_separated_string_list(&collision_paths, ", ",
2136 &collision_ent->source_files);
2137 output(opt, 1, _("CONFLICT (implicit dir rename): Existing "
2138 "file/dir at %s in the way of implicit "
2139 "directory rename(s) putting the following "
2140 "path(s) there: %s."),
2141 new_path, collision_paths.buf);
2142 clean = 0;
2143 } else if (collision_ent->source_files.nr > 1) {
2144 collision_ent->reported_already = 1;
2145 strbuf_add_separated_string_list(&collision_paths, ", ",
2146 &collision_ent->source_files);
2147 output(opt, 1, _("CONFLICT (implicit dir rename): Cannot map "
2148 "more than one path to %s; implicit directory "
2149 "renames tried to put these paths there: %s"),
2150 new_path, collision_paths.buf);
2151 clean = 0;
2152 }
2153
2154 /* Free memory we no longer need */
2155 strbuf_release(&collision_paths);
2156 if (!clean && new_path) {
2157 free(new_path);
2158 return NULL;
2159 }
2160
2161 return new_path;
2162 }
2163
2164 /*
2165 * There are a couple things we want to do at the directory level:
2166 * 1. Check for both sides renaming to the same thing, in order to avoid
2167 * implicit renaming of files that should be left in place. (See
2168 * testcase 6b in t6043 for details.)
2169 * 2. Prune directory renames if there are still files left in the
2170 * original directory. These represent a partial directory rename,
2171 * i.e. a rename where only some of the files within the directory
2172 * were renamed elsewhere. (Technically, this could be done earlier
2173 * in get_directory_renames(), except that would prevent us from
2174 * doing the previous check and thus failing testcase 6b.)
2175 * 3. Check for rename/rename(1to2) conflicts (at the directory level).
2176 * In the future, we could potentially record this info as well and
2177 * omit reporting rename/rename(1to2) conflicts for each path within
2178 * the affected directories, thus cleaning up the merge output.
2179 * NOTE: We do NOT check for rename/rename(2to1) conflicts at the
2180 * directory level, because merging directories is fine. If it
2181 * causes conflicts for files within those merged directories, then
2182 * that should be detected at the individual path level.
2183 */
2184 static void handle_directory_level_conflicts(struct merge_options *opt,
2185 struct hashmap *dir_re_head,
2186 struct tree *head,
2187 struct hashmap *dir_re_merge,
2188 struct tree *merge)
2189 {
2190 struct hashmap_iter iter;
2191 struct dir_rename_entry *head_ent;
2192 struct dir_rename_entry *merge_ent;
2193
2194 struct string_list remove_from_head = STRING_LIST_INIT_NODUP;
2195 struct string_list remove_from_merge = STRING_LIST_INIT_NODUP;
2196
2197 hashmap_for_each_entry(dir_re_head, &iter, head_ent,
2198 ent /* member name */) {
2199 merge_ent = dir_rename_find_entry(dir_re_merge, head_ent->dir);
2200 if (merge_ent &&
2201 !head_ent->non_unique_new_dir &&
2202 !merge_ent->non_unique_new_dir &&
2203 !strbuf_cmp(&head_ent->new_dir, &merge_ent->new_dir)) {
2204 /* 1. Renamed identically; remove it from both sides */
2205 string_list_append(&remove_from_head,
2206 head_ent->dir)->util = head_ent;
2207 strbuf_release(&head_ent->new_dir);
2208 string_list_append(&remove_from_merge,
2209 merge_ent->dir)->util = merge_ent;
2210 strbuf_release(&merge_ent->new_dir);
2211 } else if (tree_has_path(opt->repo, head, head_ent->dir)) {
2212 /* 2. This wasn't a directory rename after all */
2213 string_list_append(&remove_from_head,
2214 head_ent->dir)->util = head_ent;
2215 strbuf_release(&head_ent->new_dir);
2216 }
2217 }
2218
2219 remove_hashmap_entries(dir_re_head, &remove_from_head);
2220 remove_hashmap_entries(dir_re_merge, &remove_from_merge);
2221
2222 hashmap_for_each_entry(dir_re_merge, &iter, merge_ent,
2223 ent /* member name */) {
2224 head_ent = dir_rename_find_entry(dir_re_head, merge_ent->dir);
2225 if (tree_has_path(opt->repo, merge, merge_ent->dir)) {
2226 /* 2. This wasn't a directory rename after all */
2227 string_list_append(&remove_from_merge,
2228 merge_ent->dir)->util = merge_ent;
2229 } else if (head_ent &&
2230 !head_ent->non_unique_new_dir &&
2231 !merge_ent->non_unique_new_dir) {
2232 /* 3. rename/rename(1to2) */
2233 /*
2234 * We can assume it's not rename/rename(1to1) because
2235 * that was case (1), already checked above. So we
2236 * know that head_ent->new_dir and merge_ent->new_dir
2237 * are different strings.
2238 */
2239 output(opt, 1, _("CONFLICT (rename/rename): "
2240 "Rename directory %s->%s in %s. "
2241 "Rename directory %s->%s in %s"),
2242 head_ent->dir, head_ent->new_dir.buf, opt->branch1,
2243 head_ent->dir, merge_ent->new_dir.buf, opt->branch2);
2244 string_list_append(&remove_from_head,
2245 head_ent->dir)->util = head_ent;
2246 strbuf_release(&head_ent->new_dir);
2247 string_list_append(&remove_from_merge,
2248 merge_ent->dir)->util = merge_ent;
2249 strbuf_release(&merge_ent->new_dir);
2250 }
2251 }
2252
2253 remove_hashmap_entries(dir_re_head, &remove_from_head);
2254 remove_hashmap_entries(dir_re_merge, &remove_from_merge);
2255 }
2256
2257 static struct hashmap *get_directory_renames(struct diff_queue_struct *pairs)
2258 {
2259 struct hashmap *dir_renames;
2260 struct hashmap_iter iter;
2261 struct dir_rename_entry *entry;
2262 int i;
2263
2264 /*
2265 * Typically, we think of a directory rename as all files from a
2266 * certain directory being moved to a target directory. However,
2267 * what if someone first moved two files from the original
2268 * directory in one commit, and then renamed the directory
2269 * somewhere else in a later commit? At merge time, we just know
2270 * that files from the original directory went to two different
2271 * places, and that the bulk of them ended up in the same place.
2272 * We want each directory rename to represent where the bulk of the
2273 * files from that directory end up; this function exists to find
2274 * where the bulk of the files went.
2275 *
2276 * The first loop below simply iterates through the list of file
2277 * renames, finding out how often each directory rename pair
2278 * possibility occurs.
2279 */
2280 dir_renames = xmalloc(sizeof(*dir_renames));
2281 dir_rename_init(dir_renames);
2282 for (i = 0; i < pairs->nr; ++i) {
2283 struct string_list_item *item;
2284 int *count;
2285 struct diff_filepair *pair = pairs->queue[i];
2286 char *old_dir, *new_dir;
2287
2288 /* File not part of directory rename if it wasn't renamed */
2289 if (pair->status != 'R')
2290 continue;
2291
2292 get_renamed_dir_portion(pair->one->path, pair->two->path,
2293 &old_dir, &new_dir);
2294 if (!old_dir)
2295 /* Directory didn't change at all; ignore this one. */
2296 continue;
2297
2298 entry = dir_rename_find_entry(dir_renames, old_dir);
2299 if (!entry) {
2300 entry = xmalloc(sizeof(*entry));
2301 dir_rename_entry_init(entry, old_dir);
2302 hashmap_put(dir_renames, &entry->ent);
2303 } else {
2304 free(old_dir);
2305 }
2306 item = string_list_lookup(&entry->possible_new_dirs, new_dir);
2307 if (!item) {
2308 item = string_list_insert(&entry->possible_new_dirs,
2309 new_dir);
2310 item->util = xcalloc(1, sizeof(int));
2311 } else {
2312 free(new_dir);
2313 }
2314 count = item->util;
2315 *count += 1;
2316 }
2317
2318 /*
2319 * For each directory with files moved out of it, we find out which
2320 * target directory received the most files so we can declare it to
2321 * be the "winning" target location for the directory rename. This
2322 * winner gets recorded in new_dir. If there is no winner
2323 * (multiple target directories received the same number of files),
2324 * we set non_unique_new_dir. Once we've determined the winner (or
2325 * that there is no winner), we no longer need possible_new_dirs.
2326 */
2327 hashmap_for_each_entry(dir_renames, &iter, entry,
2328 ent /* member name */) {
2329 int max = 0;
2330 int bad_max = 0;
2331 char *best = NULL;
2332
2333 for (i = 0; i < entry->possible_new_dirs.nr; i++) {
2334 int *count = entry->possible_new_dirs.items[i].util;
2335
2336 if (*count == max)
2337 bad_max = max;
2338 else if (*count > max) {
2339 max = *count;
2340 best = entry->possible_new_dirs.items[i].string;
2341 }
2342 }
2343 if (bad_max == max)
2344 entry->non_unique_new_dir = 1;
2345 else {
2346 assert(entry->new_dir.len == 0);
2347 strbuf_addstr(&entry->new_dir, best);
2348 }
2349 /*
2350 * The relevant directory sub-portion of the original full
2351 * filepaths were xstrndup'ed before inserting into
2352 * possible_new_dirs, and instead of manually iterating the
2353 * list and free'ing each, just lie and tell
2354 * possible_new_dirs that it did the strdup'ing so that it
2355 * will free them for us.
2356 */
2357 entry->possible_new_dirs.strdup_strings = 1;
2358 string_list_clear(&entry->possible_new_dirs, 1);
2359 }
2360
2361 return dir_renames;
2362 }
2363
2364 static struct dir_rename_entry *check_dir_renamed(const char *path,
2365 struct hashmap *dir_renames)
2366 {
2367 char *temp = xstrdup(path);
2368 char *end;
2369 struct dir_rename_entry *entry = NULL;
2370
2371 while ((end = strrchr(temp, '/'))) {
2372 *end = '\0';
2373 entry = dir_rename_find_entry(dir_renames, temp);
2374 if (entry)
2375 break;
2376 }
2377 free(temp);
2378 return entry;
2379 }
2380
2381 static void compute_collisions(struct hashmap *collisions,
2382 struct hashmap *dir_renames,
2383 struct diff_queue_struct *pairs)
2384 {
2385 int i;
2386
2387 /*
2388 * Multiple files can be mapped to the same path due to directory
2389 * renames done by the other side of history. Since that other
2390 * side of history could have merged multiple directories into one,
2391 * if our side of history added the same file basename to each of
2392 * those directories, then all N of them would get implicitly
2393 * renamed by the directory rename detection into the same path,
2394 * and we'd get an add/add/.../add conflict, and all those adds
2395 * from *this* side of history. This is not representable in the
2396 * index, and users aren't going to easily be able to make sense of
2397 * it. So we need to provide a good warning about what's
2398 * happening, and fall back to no-directory-rename detection
2399 * behavior for those paths.
2400 *
2401 * See testcases 9e and all of section 5 from t6043 for examples.
2402 */
2403 collision_init(collisions);
2404
2405 for (i = 0; i < pairs->nr; ++i) {
2406 struct dir_rename_entry *dir_rename_ent;
2407 struct collision_entry *collision_ent;
2408 char *new_path;
2409 struct diff_filepair *pair = pairs->queue[i];
2410
2411 if (pair->status != 'A' && pair->status != 'R')
2412 continue;
2413 dir_rename_ent = check_dir_renamed(pair->two->path,
2414 dir_renames);
2415 if (!dir_rename_ent)
2416 continue;
2417
2418 new_path = apply_dir_rename(dir_rename_ent, pair->two->path);
2419 if (!new_path)
2420 /*
2421 * dir_rename_ent->non_unique_new_path is true, which
2422 * means there is no directory rename for us to use,
2423 * which means it won't cause us any additional
2424 * collisions.
2425 */
2426 continue;
2427 collision_ent = collision_find_entry(collisions, new_path);
2428 if (!collision_ent) {
2429 CALLOC_ARRAY(collision_ent, 1);
2430 hashmap_entry_init(&collision_ent->ent,
2431 strhash(new_path));
2432 hashmap_put(collisions, &collision_ent->ent);
2433 collision_ent->target_file = new_path;
2434 } else {
2435 free(new_path);
2436 }
2437 string_list_insert(&collision_ent->source_files,
2438 pair->two->path);
2439 }
2440 }
2441
2442 static char *check_for_directory_rename(struct merge_options *opt,
2443 const char *path,
2444 struct tree *tree,
2445 struct hashmap *dir_renames,
2446 struct hashmap *dir_rename_exclusions,
2447 struct hashmap *collisions,
2448 int *clean_merge)
2449 {
2450 char *new_path = NULL;
2451 struct dir_rename_entry *entry = check_dir_renamed(path, dir_renames);
2452 struct dir_rename_entry *oentry = NULL;
2453
2454 if (!entry)
2455 return new_path;
2456
2457 /*
2458 * This next part is a little weird. We do not want to do an
2459 * implicit rename into a directory we renamed on our side, because
2460 * that will result in a spurious rename/rename(1to2) conflict. An
2461 * example:
2462 * Base commit: dumbdir/afile, otherdir/bfile
2463 * Side 1: smrtdir/afile, otherdir/bfile
2464 * Side 2: dumbdir/afile, dumbdir/bfile
2465 * Here, while working on Side 1, we could notice that otherdir was
2466 * renamed/merged to dumbdir, and change the diff_filepair for
2467 * otherdir/bfile into a rename into dumbdir/bfile. However, Side
2468 * 2 will notice the rename from dumbdir to smrtdir, and do the
2469 * transitive rename to move it from dumbdir/bfile to
2470 * smrtdir/bfile. That gives us bfile in dumbdir vs being in
2471 * smrtdir, a rename/rename(1to2) conflict. We really just want
2472 * the file to end up in smrtdir. And the way to achieve that is
2473 * to not let Side1 do the rename to dumbdir, since we know that is
2474 * the source of one of our directory renames.
2475 *
2476 * That's why oentry and dir_rename_exclusions is here.
2477 *
2478 * As it turns out, this also prevents N-way transient rename
2479 * confusion; See testcases 9c and 9d of t6043.
2480 */
2481 oentry = dir_rename_find_entry(dir_rename_exclusions, entry->new_dir.buf);
2482 if (oentry) {
2483 output(opt, 1, _("WARNING: Avoiding applying %s -> %s rename "
2484 "to %s, because %s itself was renamed."),
2485 entry->dir, entry->new_dir.buf, path, entry->new_dir.buf);
2486 } else {
2487 new_path = handle_path_level_conflicts(opt, path, entry,
2488 collisions, tree);
2489 *clean_merge &= (new_path != NULL);
2490 }
2491
2492 return new_path;
2493 }
2494
2495 static void apply_directory_rename_modifications(struct merge_options *opt,
2496 struct diff_filepair *pair,
2497 char *new_path,
2498 struct rename *re,
2499 struct tree *tree,
2500 struct tree *o_tree,
2501 struct tree *a_tree,
2502 struct tree *b_tree,
2503 struct string_list *entries)
2504 {
2505 struct string_list_item *item;
2506 int stage = (tree == a_tree ? 2 : 3);
2507 int update_wd;
2508
2509 /*
2510 * In all cases where we can do directory rename detection,
2511 * unpack_trees() will have read pair->two->path into the
2512 * index and the working copy. We need to remove it so that
2513 * we can instead place it at new_path. It is guaranteed to
2514 * not be untracked (unpack_trees() would have errored out
2515 * saying the file would have been overwritten), but it might
2516 * be dirty, though.
2517 */
2518 update_wd = !was_dirty(opt, pair->two->path);
2519 if (!update_wd)
2520 output(opt, 1, _("Refusing to lose dirty file at %s"),
2521 pair->two->path);
2522 remove_file(opt, 1, pair->two->path, !update_wd);
2523
2524 /* Find or create a new re->dst_entry */
2525 item = string_list_lookup(entries, new_path);
2526 if (item) {
2527 /*
2528 * Since we're renaming on this side of history, and it's
2529 * due to a directory rename on the other side of history
2530 * (which we only allow when the directory in question no
2531 * longer exists on the other side of history), the
2532 * original entry for re->dst_entry is no longer
2533 * necessary...
2534 */
2535 re->dst_entry->processed = 1;
2536
2537 /*
2538 * ...because we'll be using this new one.
2539 */
2540 re->dst_entry = item->util;
2541 } else {
2542 /*
2543 * re->dst_entry is for the before-dir-rename path, and we
2544 * need it to hold information for the after-dir-rename
2545 * path. Before creating a new entry, we need to mark the
2546 * old one as unnecessary (...unless it is shared by
2547 * src_entry, i.e. this didn't use to be a rename, in which
2548 * case we can just allow the normal processing to happen
2549 * for it).
2550 */
2551 if (pair->status == 'R')
2552 re->dst_entry->processed = 1;
2553
2554 re->dst_entry = insert_stage_data(opt->repo, new_path,
2555 o_tree, a_tree, b_tree,
2556 entries);
2557 item = string_list_insert(entries, new_path);
2558 item->util = re->dst_entry;
2559 }
2560
2561 /*
2562 * Update the stage_data with the information about the path we are
2563 * moving into place. That slot will be empty and available for us
2564 * to write to because of the collision checks in
2565 * handle_path_level_conflicts(). In other words,
2566 * re->dst_entry->stages[stage].oid will be the null_oid, so it's
2567 * open for us to write to.
2568 *
2569 * It may be tempting to actually update the index at this point as
2570 * well, using update_stages_for_stage_data(), but as per the big
2571 * "NOTE" in update_stages(), doing so will modify the current
2572 * in-memory index which will break calls to would_lose_untracked()
2573 * that we need to make. Instead, we need to just make sure that
2574 * the various handle_rename_*() functions update the index
2575 * explicitly rather than relying on unpack_trees() to have done it.
2576 */
2577 get_tree_entry(opt->repo,
2578 &tree->object.oid,
2579 pair->two->path,
2580 &re->dst_entry->stages[stage].oid,
2581 &re->dst_entry->stages[stage].mode);
2582
2583 /*
2584 * Record the original change status (or 'type' of change). If it
2585 * was originally an add ('A'), this lets us differentiate later
2586 * between a RENAME_DELETE conflict and RENAME_VIA_DIR (they
2587 * otherwise look the same). If it was originally a rename ('R'),
2588 * this lets us remember and report accurately about the transitive
2589 * renaming that occurred via the directory rename detection. Also,
2590 * record the original destination name.
2591 */
2592 re->dir_rename_original_type = pair->status;
2593 re->dir_rename_original_dest = pair->two->path;
2594
2595 /*
2596 * We don't actually look at pair->status again, but it seems
2597 * pedagogically correct to adjust it.
2598 */
2599 pair->status = 'R';
2600
2601 /*
2602 * Finally, record the new location.
2603 */
2604 pair->two->path = new_path;
2605 }
2606
2607 /*
2608 * Get information of all renames which occurred in 'pairs', making use of
2609 * any implicit directory renames inferred from the other side of history.
2610 * We need the three trees in the merge ('o_tree', 'a_tree' and 'b_tree')
2611 * to be able to associate the correct cache entries with the rename
2612 * information; tree is always equal to either a_tree or b_tree.
2613 */
2614 static struct string_list *get_renames(struct merge_options *opt,
2615 const char *branch,
2616 struct diff_queue_struct *pairs,
2617 struct hashmap *dir_renames,
2618 struct hashmap *dir_rename_exclusions,
2619 struct tree *tree,
2620 struct tree *o_tree,
2621 struct tree *a_tree,
2622 struct tree *b_tree,
2623 struct string_list *entries,
2624 int *clean_merge)
2625 {
2626 int i;
2627 struct hashmap collisions;
2628 struct hashmap_iter iter;
2629 struct collision_entry *e;
2630 struct string_list *renames;
2631
2632 compute_collisions(&collisions, dir_renames, pairs);
2633 CALLOC_ARRAY(renames, 1);
2634
2635 for (i = 0; i < pairs->nr; ++i) {
2636 struct string_list_item *item;
2637 struct rename *re;
2638 struct diff_filepair *pair = pairs->queue[i];
2639 char *new_path; /* non-NULL only with directory renames */
2640
2641 if (pair->status != 'A' && pair->status != 'R') {
2642 diff_free_filepair(pair);
2643 continue;
2644 }
2645 new_path = check_for_directory_rename(opt, pair->two->path, tree,
2646 dir_renames,
2647 dir_rename_exclusions,
2648 &collisions,
2649 clean_merge);
2650 if (pair->status != 'R' && !new_path) {
2651 diff_free_filepair(pair);
2652 continue;
2653 }
2654
2655 re = xmalloc(sizeof(*re));
2656 re->processed = 0;
2657 re->pair = pair;
2658 re->branch = branch;
2659 re->dir_rename_original_type = '\0';
2660 re->dir_rename_original_dest = NULL;
2661 item = string_list_lookup(entries, re->pair->one->path);
2662 if (!item)
2663 re->src_entry = insert_stage_data(opt->repo,
2664 re->pair->one->path,
2665 o_tree, a_tree, b_tree, entries);
2666 else
2667 re->src_entry = item->util;
2668
2669 item = string_list_lookup(entries, re->pair->two->path);
2670 if (!item)
2671 re->dst_entry = insert_stage_data(opt->repo,
2672 re->pair->two->path,
2673 o_tree, a_tree, b_tree, entries);
2674 else
2675 re->dst_entry = item->util;
2676 item = string_list_insert(renames, pair->one->path);
2677 item->util = re;
2678 if (new_path)
2679 apply_directory_rename_modifications(opt, pair, new_path,
2680 re, tree, o_tree,
2681 a_tree, b_tree,
2682 entries);
2683 }
2684
2685 hashmap_for_each_entry(&collisions, &iter, e,
2686 ent /* member name */) {
2687 free(e->target_file);
2688 string_list_clear(&e->source_files, 0);
2689 }
2690 hashmap_clear_and_free(&collisions, struct collision_entry, ent);
2691 return renames;
2692 }
2693
2694 static int process_renames(struct merge_options *opt,
2695 struct string_list *a_renames,
2696 struct string_list *b_renames)
2697 {
2698 int clean_merge = 1, i, j;
2699 struct string_list a_by_dst = STRING_LIST_INIT_NODUP;
2700 struct string_list b_by_dst = STRING_LIST_INIT_NODUP;
2701 const struct rename *sre;
2702
2703 /*
2704 * FIXME: As string-list.h notes, it's O(n^2) to build a sorted
2705 * string_list one-by-one, but O(n log n) to build it unsorted and
2706 * then sort it. Note that as we build the list, we do not need to
2707 * check if the existing destination path is already in the list,
2708 * because the structure of diffcore_rename guarantees we won't
2709 * have duplicates.
2710 */
2711 for (i = 0; i < a_renames->nr; i++) {
2712 sre = a_renames->items[i].util;
2713 string_list_insert(&a_by_dst, sre->pair->two->path)->util
2714 = (void *)sre;
2715 }
2716 for (i = 0; i < b_renames->nr; i++) {
2717 sre = b_renames->items[i].util;
2718 string_list_insert(&b_by_dst, sre->pair->two->path)->util
2719 = (void *)sre;
2720 }
2721
2722 for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) {
2723 struct string_list *renames1, *renames2Dst;
2724 struct rename *ren1 = NULL, *ren2 = NULL;
2725 const char *ren1_src, *ren1_dst;
2726 struct string_list_item *lookup;
2727
2728 if (i >= a_renames->nr) {
2729 ren2 = b_renames->items[j++].util;
2730 } else if (j >= b_renames->nr) {
2731 ren1 = a_renames->items[i++].util;
2732 } else {
2733 int compare = strcmp(a_renames->items[i].string,
2734 b_renames->items[j].string);
2735 if (compare <= 0)
2736 ren1 = a_renames->items[i++].util;
2737 if (compare >= 0)
2738 ren2 = b_renames->items[j++].util;
2739 }
2740
2741 /* TODO: refactor, so that 1/2 are not needed */
2742 if (ren1) {
2743 renames1 = a_renames;
2744 renames2Dst = &b_by_dst;
2745 } else {
2746 renames1 = b_renames;
2747 renames2Dst = &a_by_dst;
2748 SWAP(ren2, ren1);
2749 }
2750
2751 if (ren1->processed)
2752 continue;
2753 ren1->processed = 1;
2754 ren1->dst_entry->processed = 1;
2755 /* BUG: We should only mark src_entry as processed if we
2756 * are not dealing with a rename + add-source case.
2757 */
2758 ren1->src_entry->processed = 1;
2759
2760 ren1_src = ren1->pair->one->path;
2761 ren1_dst = ren1->pair->two->path;
2762
2763 if (ren2) {
2764 /* One file renamed on both sides */
2765 const char *ren2_src = ren2->pair->one->path;
2766 const char *ren2_dst = ren2->pair->two->path;
2767 enum rename_type rename_type;
2768 if (strcmp(ren1_src, ren2_src) != 0)
2769 BUG("ren1_src != ren2_src");
2770 ren2->dst_entry->processed = 1;
2771 ren2->processed = 1;
2772 if (strcmp(ren1_dst, ren2_dst) != 0) {
2773 rename_type = RENAME_ONE_FILE_TO_TWO;
2774 clean_merge = 0;
2775 } else {
2776 rename_type = RENAME_ONE_FILE_TO_ONE;
2777 /* BUG: We should only remove ren1_src in
2778 * the base stage (think of rename +
2779 * add-source cases).
2780 */
2781 remove_file(opt, 1, ren1_src, 1);
2782 update_entry(ren1->dst_entry,
2783 ren1->pair->one,
2784 ren1->pair->two,
2785 ren2->pair->two);
2786 }
2787 setup_rename_conflict_info(rename_type, opt, ren1, ren2);
2788 } else if ((lookup = string_list_lookup(renames2Dst, ren1_dst))) {
2789 /* Two different files renamed to the same thing */
2790 char *ren2_dst;
2791 ren2 = lookup->util;
2792 ren2_dst = ren2->pair->two->path;
2793 if (strcmp(ren1_dst, ren2_dst) != 0)
2794 BUG("ren1_dst != ren2_dst");
2795
2796 clean_merge = 0;
2797 ren2->processed = 1;
2798 /*
2799 * BUG: We should only mark src_entry as processed
2800 * if we are not dealing with a rename + add-source
2801 * case.
2802 */
2803 ren2->src_entry->processed = 1;
2804
2805 setup_rename_conflict_info(RENAME_TWO_FILES_TO_ONE,
2806 opt, ren1, ren2);
2807 } else {
2808 /* Renamed in 1, maybe changed in 2 */
2809 /* we only use sha1 and mode of these */
2810 struct diff_filespec src_other, dst_other;
2811 int try_merge;
2812
2813 /*
2814 * unpack_trees loads entries from common-commit
2815 * into stage 1, from head-commit into stage 2, and
2816 * from merge-commit into stage 3. We keep track
2817 * of which side corresponds to the rename.
2818 */
2819 int renamed_stage = a_renames == renames1 ? 2 : 3;
2820 int other_stage = a_renames == renames1 ? 3 : 2;
2821
2822 /*
2823 * Directory renames have a funny corner case...
2824 */
2825 int renamed_to_self = !strcmp(ren1_src, ren1_dst);
2826
2827 /* BUG: We should only remove ren1_src in the base
2828 * stage and in other_stage (think of rename +
2829 * add-source case).
2830 */
2831 if (!renamed_to_self)
2832 remove_file(opt, 1, ren1_src,
2833 renamed_stage == 2 ||
2834 !was_tracked(opt, ren1_src));
2835
2836 oidcpy(&src_other.oid,
2837 &ren1->src_entry->stages[other_stage].oid);
2838 src_other.mode = ren1->src_entry->stages[other_stage].mode;
2839 oidcpy(&dst_other.oid,
2840 &ren1->dst_entry->stages[other_stage].oid);
2841 dst_other.mode = ren1->dst_entry->stages[other_stage].mode;
2842 try_merge = 0;
2843
2844 if (oideq(&src_other.oid, null_oid()) &&
2845 ren1->dir_rename_original_type == 'A') {
2846 setup_rename_conflict_info(RENAME_VIA_DIR,
2847 opt, ren1, NULL);
2848 } else if (renamed_to_self) {
2849 setup_rename_conflict_info(RENAME_NORMAL,
2850 opt, ren1, NULL);
2851 } else if (oideq(&src_other.oid, null_oid())) {
2852 setup_rename_conflict_info(RENAME_DELETE,
2853 opt, ren1, NULL);
2854 } else if ((dst_other.mode == ren1->pair->two->mode) &&
2855 oideq(&dst_other.oid, &ren1->pair->two->oid)) {
2856 /*
2857 * Added file on the other side identical to
2858 * the file being renamed: clean merge.
2859 * Also, there is no need to overwrite the
2860 * file already in the working copy, so call
2861 * update_file_flags() instead of
2862 * update_file().
2863 */
2864 if (update_file_flags(opt,
2865 ren1->pair->two,
2866 ren1_dst,
2867 1, /* update_cache */
2868 0 /* update_wd */))
2869 clean_merge = -1;
2870 } else if (!oideq(&dst_other.oid, null_oid())) {
2871 /*
2872 * Probably not a clean merge, but it's
2873 * premature to set clean_merge to 0 here,
2874 * because if the rename merges cleanly and
2875 * the merge exactly matches the newly added
2876 * file, then the merge will be clean.
2877 */
2878 setup_rename_conflict_info(RENAME_ADD,
2879 opt, ren1, NULL);
2880 } else
2881 try_merge = 1;
2882
2883 if (clean_merge < 0)
2884 goto cleanup_and_return;
2885 if (try_merge) {
2886 struct diff_filespec *o, *a, *b;
2887 src_other.path = (char *)ren1_src;
2888
2889 o = ren1->pair->one;
2890 if (a_renames == renames1) {
2891 a = ren1->pair->two;
2892 b = &src_other;
2893 } else {
2894 b = ren1->pair->two;
2895 a = &src_other;
2896 }
2897 update_entry(ren1->dst_entry, o, a, b);
2898 setup_rename_conflict_info(RENAME_NORMAL,
2899 opt, ren1, NULL);
2900 }
2901 }
2902 }
2903 cleanup_and_return:
2904 string_list_clear(&a_by_dst, 0);
2905 string_list_clear(&b_by_dst, 0);
2906
2907 return clean_merge;
2908 }
2909
2910 struct rename_info {
2911 struct string_list *head_renames;
2912 struct string_list *merge_renames;
2913 };
2914
2915 static void initial_cleanup_rename(struct diff_queue_struct *pairs,
2916 struct hashmap *dir_renames)
2917 {
2918 struct hashmap_iter iter;
2919 struct dir_rename_entry *e;
2920
2921 hashmap_for_each_entry(dir_renames, &iter, e,
2922 ent /* member name */) {
2923 free(e->dir);
2924 strbuf_release(&e->new_dir);
2925 /* possible_new_dirs already cleared in get_directory_renames */
2926 }
2927 hashmap_clear_and_free(dir_renames, struct dir_rename_entry, ent);
2928 free(dir_renames);
2929
2930 free(pairs->queue);
2931 free(pairs);
2932 }
2933
2934 static int detect_and_process_renames(struct merge_options *opt,
2935 struct tree *common,
2936 struct tree *head,
2937 struct tree *merge,
2938 struct string_list *entries,
2939 struct rename_info *ri)
2940 {
2941 struct diff_queue_struct *head_pairs, *merge_pairs;
2942 struct hashmap *dir_re_head, *dir_re_merge;
2943 int clean = 1;
2944
2945 ri->head_renames = NULL;
2946 ri->merge_renames = NULL;
2947
2948 if (!merge_detect_rename(opt))
2949 return 1;
2950
2951 head_pairs = get_diffpairs(opt, common, head);
2952 merge_pairs = get_diffpairs(opt, common, merge);
2953
2954 if ((opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_TRUE) ||
2955 (opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_CONFLICT &&
2956 !opt->priv->call_depth)) {
2957 dir_re_head = get_directory_renames(head_pairs);
2958 dir_re_merge = get_directory_renames(merge_pairs);
2959
2960 handle_directory_level_conflicts(opt,
2961 dir_re_head, head,
2962 dir_re_merge, merge);
2963 } else {
2964 dir_re_head = xmalloc(sizeof(*dir_re_head));
2965 dir_re_merge = xmalloc(sizeof(*dir_re_merge));
2966 dir_rename_init(dir_re_head);
2967 dir_rename_init(dir_re_merge);
2968 }
2969
2970 ri->head_renames = get_renames(opt, opt->branch1, head_pairs,
2971 dir_re_merge, dir_re_head, head,
2972 common, head, merge, entries,
2973 &clean);
2974 if (clean < 0)
2975 goto cleanup;
2976 ri->merge_renames = get_renames(opt, opt->branch2, merge_pairs,
2977 dir_re_head, dir_re_merge, merge,
2978 common, head, merge, entries,
2979 &clean);
2980 if (clean < 0)
2981 goto cleanup;
2982 clean &= process_renames(opt, ri->head_renames, ri->merge_renames);
2983
2984 cleanup:
2985 /*
2986 * Some cleanup is deferred until cleanup_renames() because the
2987 * data structures are still needed and referenced in
2988 * process_entry(). But there are a few things we can free now.
2989 */
2990 initial_cleanup_rename(head_pairs, dir_re_head);
2991 initial_cleanup_rename(merge_pairs, dir_re_merge);
2992
2993 return clean;
2994 }
2995
2996 static void final_cleanup_rename(struct string_list *rename)
2997 {
2998 const struct rename *re;
2999 int i;
3000
3001 if (!rename)
3002 return;
3003
3004 for (i = 0; i < rename->nr; i++) {
3005 re = rename->items[i].util;
3006 diff_free_filepair(re->pair);
3007 }
3008 string_list_clear(rename, 1);
3009 free(rename);
3010 }
3011
3012 static void final_cleanup_renames(struct rename_info *re_info)
3013 {
3014 final_cleanup_rename(re_info->head_renames);
3015 final_cleanup_rename(re_info->merge_renames);
3016 }
3017
3018 static int read_oid_strbuf(struct merge_options *opt,
3019 const struct object_id *oid,
3020 struct strbuf *dst)
3021 {
3022 void *buf;
3023 enum object_type type;
3024 unsigned long size;
3025 buf = read_object_file(oid, &type, &size);
3026 if (!buf)
3027 return err(opt, _("cannot read object %s"), oid_to_hex(oid));
3028 if (type != OBJ_BLOB) {
3029 free(buf);
3030 return err(opt, _("object %s is not a blob"), oid_to_hex(oid));
3031 }
3032 strbuf_attach(dst, buf, size, size + 1);
3033 return 0;
3034 }
3035
3036 static int blob_unchanged(struct merge_options *opt,
3037 const struct diff_filespec *o,
3038 const struct diff_filespec *a,
3039 int renormalize, const char *path)
3040 {
3041 struct strbuf obuf = STRBUF_INIT;
3042 struct strbuf abuf = STRBUF_INIT;
3043 int ret = 0; /* assume changed for safety */
3044 struct index_state *idx = opt->repo->index;
3045
3046 if (a->mode != o->mode)
3047 return 0;
3048 if (oideq(&o->oid, &a->oid))
3049 return 1;
3050 if (!renormalize)
3051 return 0;
3052
3053 if (read_oid_strbuf(opt, &o->oid, &obuf) ||
3054 read_oid_strbuf(opt, &a->oid, &abuf))
3055 goto error_return;
3056 /*
3057 * Note: binary | is used so that both renormalizations are
3058 * performed. Comparison can be skipped if both files are
3059 * unchanged since their sha1s have already been compared.
3060 */
3061 if (renormalize_buffer(idx, path, obuf.buf, obuf.len, &obuf) |
3062 renormalize_buffer(idx, path, abuf.buf, abuf.len, &abuf))
3063 ret = (obuf.len == abuf.len && !memcmp(obuf.buf, abuf.buf, obuf.len));
3064
3065 error_return:
3066 strbuf_release(&obuf);
3067 strbuf_release(&abuf);
3068 return ret;
3069 }
3070
3071 static int handle_modify_delete(struct merge_options *opt,
3072 const char *path,
3073 const struct diff_filespec *o,
3074 const struct diff_filespec *a,
3075 const struct diff_filespec *b)
3076 {
3077 const char *modify_branch, *delete_branch;
3078 const struct diff_filespec *changed;
3079
3080 if (is_valid(a)) {
3081 modify_branch = opt->branch1;
3082 delete_branch = opt->branch2;
3083 changed = a;
3084 } else {
3085 modify_branch = opt->branch2;
3086 delete_branch = opt->branch1;
3087 changed = b;
3088 }
3089
3090 return handle_change_delete(opt,
3091 path, NULL,
3092 o, changed,
3093 modify_branch, delete_branch,
3094 _("modify"), _("modified"));
3095 }
3096
3097 static int handle_content_merge(struct merge_file_info *mfi,
3098 struct merge_options *opt,
3099 const char *path,
3100 int is_dirty,
3101 const struct diff_filespec *o,
3102 const struct diff_filespec *a,
3103 const struct diff_filespec *b,
3104 struct rename_conflict_info *ci)
3105 {
3106 const char *reason = _("content");
3107 unsigned df_conflict_remains = 0;
3108
3109 if (!is_valid(o))
3110 reason = _("add/add");
3111
3112 assert(o->path && a->path && b->path);
3113 if (ci && dir_in_way(opt->repo->index, path, !opt->priv->call_depth,
3114 S_ISGITLINK(ci->ren1->pair->two->mode)))
3115 df_conflict_remains = 1;
3116
3117 if (merge_mode_and_contents(opt, o, a, b, path,
3118 opt->branch1, opt->branch2,
3119 opt->priv->call_depth * 2, mfi))
3120 return -1;
3121
3122 /*
3123 * We can skip updating the working tree file iff:
3124 * a) The merge is clean
3125 * b) The merge matches what was in HEAD (content, mode, pathname)
3126 * c) The target path is usable (i.e. not involved in D/F conflict)
3127 */
3128 if (mfi->clean && was_tracked_and_matches(opt, path, &mfi->blob) &&
3129 !df_conflict_remains) {
3130 int pos;
3131 struct cache_entry *ce;
3132
3133 output(opt, 3, _("Skipped %s (merged same as existing)"), path);
3134 if (add_cacheinfo(opt, &mfi->blob, path,
3135 0, (!opt->priv->call_depth && !is_dirty), 0))
3136 return -1;
3137 /*
3138 * However, add_cacheinfo() will delete the old cache entry
3139 * and add a new one. We need to copy over any skip_worktree
3140 * flag to avoid making the file appear as if it were
3141 * deleted by the user.
3142 */
3143 pos = index_name_pos(&opt->priv->orig_index, path, strlen(path));
3144 ce = opt->priv->orig_index.cache[pos];
3145 if (ce_skip_worktree(ce)) {
3146 pos = index_name_pos(opt->repo->index, path, strlen(path));
3147 ce = opt->repo->index->cache[pos];
3148 ce->ce_flags |= CE_SKIP_WORKTREE;
3149 }
3150 return mfi->clean;
3151 }
3152
3153 if (!mfi->clean) {
3154 if (S_ISGITLINK(mfi->blob.mode))
3155 reason = _("submodule");
3156 output(opt, 1, _("CONFLICT (%s): Merge conflict in %s"),
3157 reason, path);
3158 if (ci && !df_conflict_remains)
3159 if (update_stages(opt, path, o, a, b))
3160 return -1;
3161 }
3162
3163 if (df_conflict_remains || is_dirty) {
3164 char *new_path;
3165 if (opt->priv->call_depth) {
3166 remove_file_from_index(opt->repo->index, path);
3167 } else {
3168 if (!mfi->clean) {
3169 if (update_stages(opt, path, o, a, b))
3170 return -1;
3171 } else {
3172 int file_from_stage2 = was_tracked(opt, path);
3173
3174 if (update_stages(opt, path, NULL,
3175 file_from_stage2 ? &mfi->blob : NULL,
3176 file_from_stage2 ? NULL : &mfi->blob))
3177 return -1;
3178 }
3179
3180 }
3181 new_path = unique_path(opt, path, ci->ren1->branch);
3182 if (is_dirty) {
3183 output(opt, 1, _("Refusing to lose dirty file at %s"),
3184 path);
3185 }
3186 output(opt, 1, _("Adding as %s instead"), new_path);
3187 if (update_file(opt, 0, &mfi->blob, new_path)) {
3188 free(new_path);
3189 return -1;
3190 }
3191 free(new_path);
3192 mfi->clean = 0;
3193 } else if (update_file(opt, mfi->clean, &mfi->blob, path))
3194 return -1;
3195 return !is_dirty && mfi->clean;
3196 }
3197
3198 static int handle_rename_normal(struct merge_options *opt,
3199 const char *path,
3200 const struct diff_filespec *o,
3201 const struct diff_filespec *a,
3202 const struct diff_filespec *b,
3203 struct rename_conflict_info *ci)
3204 {
3205 struct rename *ren = ci->ren1;
3206 struct merge_file_info mfi;
3207 int clean;
3208
3209 /* Merge the content and write it out */
3210 clean = handle_content_merge(&mfi, opt, path, was_dirty(opt, path),
3211 o, a, b, ci);
3212
3213 if (clean &&
3214 opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_CONFLICT &&
3215 ren->dir_rename_original_dest) {
3216 if (update_stages(opt, path,
3217 &mfi.blob, &mfi.blob, &mfi.blob))
3218 return -1;
3219 clean = 0; /* not clean, but conflicted */
3220 }
3221 return clean;
3222 }
3223
3224 static void dir_rename_warning(const char *msg,
3225 int is_add,
3226 int clean,
3227 struct merge_options *opt,
3228 struct rename *ren)
3229 {
3230 const char *other_branch;
3231 other_branch = (ren->branch == opt->branch1 ?
3232 opt->branch2 : opt->branch1);
3233 if (is_add) {
3234 output(opt, clean ? 2 : 1, msg,
3235 ren->pair->one->path, ren->branch,
3236 other_branch, ren->pair->two->path);
3237 return;
3238 }
3239 output(opt, clean ? 2 : 1, msg,
3240 ren->pair->one->path, ren->dir_rename_original_dest, ren->branch,
3241 other_branch, ren->pair->two->path);
3242 }
3243 static int warn_about_dir_renamed_entries(struct merge_options *opt,
3244 struct rename *ren)
3245 {
3246 const char *msg;
3247 int clean = 1, is_add;
3248
3249 if (!ren)
3250 return clean;
3251
3252 /* Return early if ren was not affected/created by a directory rename */
3253 if (!ren->dir_rename_original_dest)
3254 return clean;
3255
3256 /* Sanity checks */
3257 assert(opt->detect_directory_renames > MERGE_DIRECTORY_RENAMES_NONE);
3258 assert(ren->dir_rename_original_type == 'A' ||
3259 ren->dir_rename_original_type == 'R');
3260
3261 /* Check whether to treat directory renames as a conflict */
3262 clean = (opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_TRUE);
3263
3264 is_add = (ren->dir_rename_original_type == 'A');
3265 if (ren->dir_rename_original_type == 'A' && clean) {
3266 msg = _("Path updated: %s added in %s inside a "
3267 "directory that was renamed in %s; moving it to %s.");
3268 } else if (ren->dir_rename_original_type == 'A' && !clean) {
3269 msg = _("CONFLICT (file location): %s added in %s "
3270 "inside a directory that was renamed in %s, "
3271 "suggesting it should perhaps be moved to %s.");
3272 } else if (ren->dir_rename_original_type == 'R' && clean) {
3273 msg = _("Path updated: %s renamed to %s in %s, inside a "
3274 "directory that was renamed in %s; moving it to %s.");
3275 } else if (ren->dir_rename_original_type == 'R' && !clean) {
3276 msg = _("CONFLICT (file location): %s renamed to %s in %s, "
3277 "inside a directory that was renamed in %s, "
3278 "suggesting it should perhaps be moved to %s.");
3279 } else {
3280 BUG("Impossible dir_rename_original_type/clean combination");
3281 }
3282 dir_rename_warning(msg, is_add, clean, opt, ren);
3283
3284 return clean;
3285 }
3286
3287 /* Per entry merge function */
3288 static int process_entry(struct merge_options *opt,
3289 const char *path, struct stage_data *entry)
3290 {
3291 int clean_merge = 1;
3292 int normalize = opt->renormalize;
3293
3294 struct diff_filespec *o = &entry->stages[1];
3295 struct diff_filespec *a = &entry->stages[2];
3296 struct diff_filespec *b = &entry->stages[3];
3297 int o_valid = is_valid(o);
3298 int a_valid = is_valid(a);
3299 int b_valid = is_valid(b);
3300 o->path = a->path = b->path = (char*)path;
3301
3302 entry->processed = 1;
3303 if (entry->rename_conflict_info) {
3304 struct rename_conflict_info *ci = entry->rename_conflict_info;
3305 struct diff_filespec *temp;
3306 int path_clean;
3307
3308 path_clean = warn_about_dir_renamed_entries(opt, ci->ren1);
3309 path_clean &= warn_about_dir_renamed_entries(opt, ci->ren2);
3310
3311 /*
3312 * For cases with a single rename, {o,a,b}->path have all been
3313 * set to the rename target path; we need to set two of these
3314 * back to the rename source.
3315 * For rename/rename conflicts, we'll manually fix paths below.
3316 */
3317 temp = (opt->branch1 == ci->ren1->branch) ? b : a;
3318 o->path = temp->path = ci->ren1->pair->one->path;
3319 if (ci->ren2) {
3320 assert(opt->branch1 == ci->ren1->branch);
3321 }
3322
3323 switch (ci->rename_type) {
3324 case RENAME_NORMAL:
3325 case RENAME_ONE_FILE_TO_ONE:
3326 clean_merge = handle_rename_normal(opt, path, o, a, b,
3327 ci);
3328 break;
3329 case RENAME_VIA_DIR:
3330 clean_merge = handle_rename_via_dir(opt, ci);
3331 break;
3332 case RENAME_ADD:
3333 /*
3334 * Probably unclean merge, but if the renamed file
3335 * merges cleanly and the result can then be
3336 * two-way merged cleanly with the added file, I
3337 * guess it's a clean merge?
3338 */
3339 clean_merge = handle_rename_add(opt, ci);
3340 break;
3341 case RENAME_DELETE:
3342 clean_merge = 0;
3343 if (handle_rename_delete(opt, ci))
3344 clean_merge = -1;
3345 break;
3346 case RENAME_ONE_FILE_TO_TWO:
3347 /*
3348 * Manually fix up paths; note:
3349 * ren[12]->pair->one->path are equal.
3350 */
3351 o->path = ci->ren1->pair->one->path;
3352 a->path = ci->ren1->pair->two->path;
3353 b->path = ci->ren2->pair->two->path;
3354
3355 clean_merge = 0;
3356 if (handle_rename_rename_1to2(opt, ci))
3357 clean_merge = -1;
3358 break;
3359 case RENAME_TWO_FILES_TO_ONE:
3360 /*
3361 * Manually fix up paths; note,
3362 * ren[12]->pair->two->path are actually equal.
3363 */
3364 o->path = NULL;
3365 a->path = ci->ren1->pair->two->path;
3366 b->path = ci->ren2->pair->two->path;
3367
3368 /*
3369 * Probably unclean merge, but if the two renamed
3370 * files merge cleanly and the two resulting files
3371 * can then be two-way merged cleanly, I guess it's
3372 * a clean merge?
3373 */
3374 clean_merge = handle_rename_rename_2to1(opt, ci);
3375 break;
3376 default:
3377 entry->processed = 0;
3378 break;
3379 }
3380 if (path_clean < clean_merge)
3381 clean_merge = path_clean;
3382 } else if (o_valid && (!a_valid || !b_valid)) {
3383 /* Case A: Deleted in one */
3384 if ((!a_valid && !b_valid) ||
3385 (!b_valid && blob_unchanged(opt, o, a, normalize, path)) ||
3386 (!a_valid && blob_unchanged(opt, o, b, normalize, path))) {
3387 /* Deleted in both or deleted in one and
3388 * unchanged in the other */
3389 if (a_valid)
3390 output(opt, 2, _("Removing %s"), path);
3391 /* do not touch working file if it did not exist */
3392 remove_file(opt, 1, path, !a_valid);
3393 } else {
3394 /* Modify/delete; deleted side may have put a directory in the way */
3395 clean_merge = 0;
3396 if (handle_modify_delete(opt, path, o, a, b))
3397 clean_merge = -1;
3398 }
3399 } else if ((!o_valid && a_valid && !b_valid) ||
3400 (!o_valid && !a_valid && b_valid)) {
3401 /* Case B: Added in one. */
3402 /* [nothing|directory] -> ([nothing|directory], file) */
3403
3404 const char *add_branch;
3405 const char *other_branch;
3406 const char *conf;
3407 const struct diff_filespec *contents;
3408
3409 if (a_valid) {
3410 add_branch = opt->branch1;
3411 other_branch = opt->branch2;
3412 contents = a;
3413 conf = _("file/directory");
3414 } else {
3415 add_branch = opt->branch2;
3416 other_branch = opt->branch1;
3417 contents = b;
3418 conf = _("directory/file");
3419 }
3420 if (dir_in_way(opt->repo->index, path,
3421 !opt->priv->call_depth && !S_ISGITLINK(a->mode),
3422 0)) {
3423 char *new_path = unique_path(opt, path, add_branch);
3424 clean_merge = 0;
3425 output(opt, 1, _("CONFLICT (%s): There is a directory with name %s in %s. "
3426 "Adding %s as %s"),
3427 conf, path, other_branch, path, new_path);
3428 if (update_file(opt, 0, contents, new_path))
3429 clean_merge = -1;
3430 else if (opt->priv->call_depth)
3431 remove_file_from_index(opt->repo->index, path);
3432 free(new_path);
3433 } else {
3434 output(opt, 2, _("Adding %s"), path);
3435 /* do not overwrite file if already present */
3436 if (update_file_flags(opt, contents, path, 1, !a_valid))
3437 clean_merge = -1;
3438 }
3439 } else if (a_valid && b_valid) {
3440 if (!o_valid) {
3441 /* Case C: Added in both (check for same permissions) */
3442 output(opt, 1,
3443 _("CONFLICT (add/add): Merge conflict in %s"),
3444 path);
3445 clean_merge = handle_file_collision(opt,
3446 path, NULL, NULL,
3447 opt->branch1,
3448 opt->branch2,
3449 a, b);
3450 } else {
3451 /* case D: Modified in both, but differently. */
3452 struct merge_file_info mfi;
3453 int is_dirty = 0; /* unpack_trees would have bailed if dirty */
3454 clean_merge = handle_content_merge(&mfi, opt, path,
3455 is_dirty,
3456 o, a, b, NULL);
3457 }
3458 } else if (!o_valid && !a_valid && !b_valid) {
3459 /*
3460 * this entry was deleted altogether. a_mode == 0 means
3461 * we had that path and want to actively remove it.
3462 */
3463 remove_file(opt, 1, path, !a->mode);
3464 } else
3465 BUG("fatal merge failure, shouldn't happen.");
3466
3467 return clean_merge;
3468 }
3469
3470 static int merge_trees_internal(struct merge_options *opt,
3471 struct tree *head,
3472 struct tree *merge,
3473 struct tree *merge_base,
3474 struct tree **result)
3475 {
3476 struct index_state *istate = opt->repo->index;
3477 int code, clean;
3478
3479 if (opt->subtree_shift) {
3480 merge = shift_tree_object(opt->repo, head, merge,
3481 opt->subtree_shift);
3482 merge_base = shift_tree_object(opt->repo, head, merge_base,
3483 opt->subtree_shift);
3484 }
3485
3486 if (oideq(&merge_base->object.oid, &merge->object.oid)) {
3487 output(opt, 0, _("Already up to date."));
3488 *result = head;
3489 return 1;
3490 }
3491
3492 code = unpack_trees_start(opt, merge_base, head, merge);
3493
3494 if (code != 0) {
3495 if (show(opt, 4) || opt->priv->call_depth)
3496 err(opt, _("merging of trees %s and %s failed"),
3497 oid_to_hex(&head->object.oid),
3498 oid_to_hex(&merge->object.oid));
3499 unpack_trees_finish(opt);
3500 return -1;
3501 }
3502
3503 if (unmerged_index(istate)) {
3504 struct string_list *entries;
3505 struct rename_info re_info;
3506 int i;
3507 /*
3508 * Only need the hashmap while processing entries, so
3509 * initialize it here and free it when we are done running
3510 * through the entries. Keeping it in the merge_options as
3511 * opposed to decaring a local hashmap is for convenience
3512 * so that we don't have to pass it to around.
3513 */
3514 hashmap_init(&opt->priv->current_file_dir_set, path_hashmap_cmp,
3515 NULL, 512);
3516 get_files_dirs(opt, head);
3517 get_files_dirs(opt, merge);
3518
3519 entries = get_unmerged(opt->repo->index);
3520 clean = detect_and_process_renames(opt, merge_base, head, merge,
3521 entries, &re_info);
3522 record_df_conflict_files(opt, entries);
3523 if (clean < 0)
3524 goto cleanup;
3525 for (i = entries->nr-1; 0 <= i; i--) {
3526 const char *path = entries->items[i].string;
3527 struct stage_data *e = entries->items[i].util;
3528 if (!e->processed) {
3529 int ret = process_entry(opt, path, e);
3530 if (!ret)
3531 clean = 0;
3532 else if (ret < 0) {
3533 clean = ret;
3534 goto cleanup;
3535 }
3536 }
3537 }
3538 for (i = 0; i < entries->nr; i++) {
3539 struct stage_data *e = entries->items[i].util;
3540 if (!e->processed)
3541 BUG("unprocessed path??? %s",
3542 entries->items[i].string);
3543 }
3544
3545 cleanup:
3546 final_cleanup_renames(&re_info);
3547
3548 string_list_clear(entries, 1);
3549 free(entries);
3550
3551 hashmap_clear_and_free(&opt->priv->current_file_dir_set,
3552 struct path_hashmap_entry, e);
3553
3554 if (clean < 0) {
3555 unpack_trees_finish(opt);
3556 return clean;
3557 }
3558 }
3559 else
3560 clean = 1;
3561
3562 unpack_trees_finish(opt);
3563
3564 if (opt->priv->call_depth &&
3565 !(*result = write_in_core_index_as_tree(opt->repo)))
3566 return -1;
3567
3568 return clean;
3569 }
3570
3571 /*
3572 * Merge the commits h1 and h2, returning a flag (int) indicating the
3573 * cleanness of the merge. Also, if opt->priv->call_depth, create a
3574 * virtual commit and write its location to *result.
3575 */
3576 static int merge_recursive_internal(struct merge_options *opt,
3577 struct commit *h1,
3578 struct commit *h2,
3579 struct commit_list *merge_bases,
3580 struct commit **result)
3581 {
3582 struct commit_list *iter;
3583 struct commit *merged_merge_bases;
3584 struct tree *result_tree;
3585 int clean;
3586 const char *ancestor_name;
3587 struct strbuf merge_base_abbrev = STRBUF_INIT;
3588
3589 if (show(opt, 4)) {
3590 output(opt, 4, _("Merging:"));
3591 output_commit_title(opt, h1);
3592 output_commit_title(opt, h2);
3593 }
3594
3595 if (!merge_bases) {
3596 merge_bases = get_merge_bases(h1, h2);
3597 merge_bases = reverse_commit_list(merge_bases);
3598 }
3599
3600 if (show(opt, 5)) {
3601 unsigned cnt = commit_list_count(merge_bases);
3602
3603 output(opt, 5, Q_("found %u common ancestor:",
3604 "found %u common ancestors:", cnt), cnt);
3605 for (iter = merge_bases; iter; iter = iter->next)
3606 output_commit_title(opt, iter->item);
3607 }
3608
3609 merged_merge_bases = pop_commit(&merge_bases);
3610 if (!merged_merge_bases) {
3611 /* if there is no common ancestor, use an empty tree */
3612 struct tree *tree;
3613
3614 tree = lookup_tree(opt->repo, opt->repo->hash_algo->empty_tree);
3615 merged_merge_bases = make_virtual_commit(opt->repo, tree,
3616 "ancestor");
3617 ancestor_name = "empty tree";
3618 } else if (opt->ancestor && !opt->priv->call_depth) {
3619 ancestor_name = opt->ancestor;
3620 } else if (merge_bases) {
3621 ancestor_name = "merged common ancestors";
3622 } else {
3623 strbuf_add_unique_abbrev(&merge_base_abbrev,
3624 &merged_merge_bases->object.oid,
3625 DEFAULT_ABBREV);
3626 ancestor_name = merge_base_abbrev.buf;
3627 }
3628
3629 for (iter = merge_bases; iter; iter = iter->next) {
3630 const char *saved_b1, *saved_b2;
3631 opt->priv->call_depth++;
3632 /*
3633 * When the merge fails, the result contains files
3634 * with conflict markers. The cleanness flag is
3635 * ignored (unless indicating an error), it was never
3636 * actually used, as result of merge_trees has always
3637 * overwritten it: the committed "conflicts" were
3638 * already resolved.
3639 */
3640 discard_index(opt->repo->index);
3641 saved_b1 = opt->branch1;
3642 saved_b2 = opt->branch2;
3643 opt->branch1 = "Temporary merge branch 1";
3644 opt->branch2 = "Temporary merge branch 2";
3645 if (merge_recursive_internal(opt, merged_merge_bases, iter->item,
3646 NULL, &merged_merge_bases) < 0)
3647 return -1;
3648 opt->branch1 = saved_b1;
3649 opt->branch2 = saved_b2;
3650 opt->priv->call_depth--;
3651
3652 if (!merged_merge_bases)
3653 return err(opt, _("merge returned no commit"));
3654 }
3655
3656 /*
3657 * FIXME: Since merge_recursive_internal() is only ever called by
3658 * places that ensure the index is loaded first
3659 * (e.g. builtin/merge.c, rebase/sequencer, etc.), in the common
3660 * case where the merge base was unique that means when we get here
3661 * we immediately discard the index and re-read it, which is a
3662 * complete waste of time. We should only be discarding and
3663 * re-reading if we were forced to recurse.
3664 */
3665 discard_index(opt->repo->index);
3666 if (!opt->priv->call_depth)
3667 repo_read_index(opt->repo);
3668
3669 opt->ancestor = ancestor_name;
3670 clean = merge_trees_internal(opt,
3671 repo_get_commit_tree(opt->repo, h1),
3672 repo_get_commit_tree(opt->repo, h2),
3673 repo_get_commit_tree(opt->repo,
3674 merged_merge_bases),
3675 &result_tree);
3676 strbuf_release(&merge_base_abbrev);
3677 opt->ancestor = NULL; /* avoid accidental re-use of opt->ancestor */
3678 if (clean < 0) {
3679 flush_output(opt);
3680 return clean;
3681 }
3682
3683 if (opt->priv->call_depth) {
3684 *result = make_virtual_commit(opt->repo, result_tree,
3685 "merged tree");
3686 commit_list_insert(h1, &(*result)->parents);
3687 commit_list_insert(h2, &(*result)->parents->next);
3688 }
3689 return clean;
3690 }
3691
3692 static int merge_start(struct merge_options *opt, struct tree *head)
3693 {
3694 struct strbuf sb = STRBUF_INIT;
3695
3696 /* Sanity checks on opt */
3697 assert(opt->repo);
3698
3699 assert(opt->branch1 && opt->branch2);
3700
3701 assert(opt->detect_renames >= -1 &&
3702 opt->detect_renames <= DIFF_DETECT_COPY);
3703 assert(opt->detect_directory_renames >= MERGE_DIRECTORY_RENAMES_NONE &&
3704 opt->detect_directory_renames <= MERGE_DIRECTORY_RENAMES_TRUE);
3705 assert(opt->rename_limit >= -1);
3706 assert(opt->rename_score >= 0 && opt->rename_score <= MAX_SCORE);
3707 assert(opt->show_rename_progress >= 0 && opt->show_rename_progress <= 1);
3708
3709 assert(opt->xdl_opts >= 0);
3710 assert(opt->recursive_variant >= MERGE_VARIANT_NORMAL &&
3711 opt->recursive_variant <= MERGE_VARIANT_THEIRS);
3712
3713 assert(opt->verbosity >= 0 && opt->verbosity <= 5);
3714 assert(opt->buffer_output <= 2);
3715 assert(opt->obuf.len == 0);
3716
3717 assert(opt->priv == NULL);
3718
3719 /* Not supported; option specific to merge-ort */
3720 assert(!opt->record_conflict_msgs_as_headers);
3721 assert(!opt->msg_header_prefix);
3722
3723 /* Sanity check on repo state; index must match head */
3724 if (repo_index_has_changes(opt->repo, head, &sb)) {
3725 err(opt, _("Your local changes to the following files would be overwritten by merge:\n %s"),
3726 sb.buf);
3727 strbuf_release(&sb);
3728 return -1;
3729 }
3730
3731 CALLOC_ARRAY(opt->priv, 1);
3732 string_list_init_dup(&opt->priv->df_conflict_file_set);
3733 return 0;
3734 }
3735
3736 static void merge_finalize(struct merge_options *opt)
3737 {
3738 flush_output(opt);
3739 if (!opt->priv->call_depth && opt->buffer_output < 2)
3740 strbuf_release(&opt->obuf);
3741 if (show(opt, 2))
3742 diff_warn_rename_limit("merge.renamelimit",
3743 opt->priv->needed_rename_limit, 0);
3744 FREE_AND_NULL(opt->priv);
3745 }
3746
3747 int merge_trees(struct merge_options *opt,
3748 struct tree *head,
3749 struct tree *merge,
3750 struct tree *merge_base)
3751 {
3752 int clean;
3753 struct tree *ignored;
3754
3755 assert(opt->ancestor != NULL);
3756
3757 if (merge_start(opt, head))
3758 return -1;
3759 clean = merge_trees_internal(opt, head, merge, merge_base, &ignored);
3760 merge_finalize(opt);
3761
3762 return clean;
3763 }
3764
3765 int merge_recursive(struct merge_options *opt,
3766 struct commit *h1,
3767 struct commit *h2,
3768 struct commit_list *merge_bases,
3769 struct commit **result)
3770 {
3771 int clean;
3772
3773 assert(opt->ancestor == NULL ||
3774 !strcmp(opt->ancestor, "constructed merge base"));
3775
3776 prepare_repo_settings(opt->repo);
3777 opt->repo->settings.command_requires_full_index = 1;
3778
3779 if (merge_start(opt, repo_get_commit_tree(opt->repo, h1)))
3780 return -1;
3781 clean = merge_recursive_internal(opt, h1, h2, merge_bases, result);
3782 merge_finalize(opt);
3783
3784 return clean;
3785 }
3786
3787 static struct commit *get_ref(struct repository *repo,
3788 const struct object_id *oid,
3789 const char *name)
3790 {
3791 struct object *object;
3792
3793 object = deref_tag(repo, parse_object(repo, oid),
3794 name, strlen(name));
3795 if (!object)
3796 return NULL;
3797 if (object->type == OBJ_TREE)
3798 return make_virtual_commit(repo, (struct tree*)object, name);
3799 if (object->type != OBJ_COMMIT)
3800 return NULL;
3801 if (parse_commit((struct commit *)object))
3802 return NULL;
3803 return (struct commit *)object;
3804 }
3805
3806 int merge_recursive_generic(struct merge_options *opt,
3807 const struct object_id *head,
3808 const struct object_id *merge,
3809 int num_merge_bases,
3810 const struct object_id **merge_bases,
3811 struct commit **result)
3812 {
3813 int clean;
3814 struct lock_file lock = LOCK_INIT;
3815 struct commit *head_commit = get_ref(opt->repo, head, opt->branch1);
3816 struct commit *next_commit = get_ref(opt->repo, merge, opt->branch2);
3817 struct commit_list *ca = NULL;
3818
3819 if (merge_bases) {
3820 int i;
3821 for (i = 0; i < num_merge_bases; ++i) {
3822 struct commit *base;
3823 if (!(base = get_ref(opt->repo, merge_bases[i],
3824 oid_to_hex(merge_bases[i]))))
3825 return err(opt, _("Could not parse object '%s'"),
3826 oid_to_hex(merge_bases[i]));
3827 commit_list_insert(base, &ca);
3828 }
3829 if (num_merge_bases == 1)
3830 opt->ancestor = "constructed merge base";
3831 }
3832
3833 repo_hold_locked_index(opt->repo, &lock, LOCK_DIE_ON_ERROR);
3834 clean = merge_recursive(opt, head_commit, next_commit, ca,
3835 result);
3836 if (clean < 0) {
3837 rollback_lock_file(&lock);
3838 return clean;
3839 }
3840
3841 if (write_locked_index(opt->repo->index, &lock,
3842 COMMIT_LOCK | SKIP_IF_UNCHANGED))
3843 return err(opt, _("Unable to write index."));
3844
3845 return clean ? 0 : 1;
3846 }
3847
3848 static void merge_recursive_config(struct merge_options *opt)
3849 {
3850 char *value = NULL;
3851 int renormalize = 0;
3852 git_config_get_int("merge.verbosity", &opt->verbosity);
3853 git_config_get_int("diff.renamelimit", &opt->rename_limit);
3854 git_config_get_int("merge.renamelimit", &opt->rename_limit);
3855 git_config_get_bool("merge.renormalize", &renormalize);
3856 opt->renormalize = renormalize;
3857 if (!git_config_get_string("diff.renames", &value)) {
3858 opt->detect_renames = git_config_rename("diff.renames", value);
3859 free(value);
3860 }
3861 if (!git_config_get_string("merge.renames", &value)) {
3862 opt->detect_renames = git_config_rename("merge.renames", value);
3863 free(value);
3864 }
3865 if (!git_config_get_string("merge.directoryrenames", &value)) {
3866 int boolval = git_parse_maybe_bool(value);
3867 if (0 <= boolval) {
3868 opt->detect_directory_renames = boolval ?
3869 MERGE_DIRECTORY_RENAMES_TRUE :
3870 MERGE_DIRECTORY_RENAMES_NONE;
3871 } else if (!strcasecmp(value, "conflict")) {
3872 opt->detect_directory_renames =
3873 MERGE_DIRECTORY_RENAMES_CONFLICT;
3874 } /* avoid erroring on values from future versions of git */
3875 free(value);
3876 }
3877 git_config(git_xmerge_config, NULL);
3878 }
3879
3880 void init_merge_options(struct merge_options *opt,
3881 struct repository *repo)
3882 {
3883 const char *merge_verbosity;
3884 memset(opt, 0, sizeof(struct merge_options));
3885
3886 opt->repo = repo;
3887
3888 opt->detect_renames = -1;
3889 opt->detect_directory_renames = MERGE_DIRECTORY_RENAMES_CONFLICT;
3890 opt->rename_limit = -1;
3891
3892 opt->verbosity = 2;
3893 opt->buffer_output = 1;
3894 strbuf_init(&opt->obuf, 0);
3895
3896 opt->renormalize = 0;
3897
3898 merge_recursive_config(opt);
3899 merge_verbosity = getenv("GIT_MERGE_VERBOSITY");
3900 if (merge_verbosity)
3901 opt->verbosity = strtol(merge_verbosity, NULL, 10);
3902 if (opt->verbosity >= 5)
3903 opt->buffer_output = 0;
3904 }
3905
3906 int parse_merge_opt(struct merge_options *opt, const char *s)
3907 {
3908 const char *arg;
3909
3910 if (!s || !*s)
3911 return -1;
3912 if (!strcmp(s, "ours"))
3913 opt->recursive_variant = MERGE_VARIANT_OURS;
3914 else if (!strcmp(s, "theirs"))
3915 opt->recursive_variant = MERGE_VARIANT_THEIRS;
3916 else if (!strcmp(s, "subtree"))
3917 opt->subtree_shift = "";
3918 else if (skip_prefix(s, "subtree=", &arg))
3919 opt->subtree_shift = arg;
3920 else if (!strcmp(s, "patience"))
3921 opt->xdl_opts = DIFF_WITH_ALG(opt, PATIENCE_DIFF);
3922 else if (!strcmp(s, "histogram"))
3923 opt->xdl_opts = DIFF_WITH_ALG(opt, HISTOGRAM_DIFF);
3924 else if (skip_prefix(s, "diff-algorithm=", &arg)) {
3925 long value = parse_algorithm_value(arg);
3926 if (value < 0)
3927 return -1;
3928 /* clear out previous settings */
3929 DIFF_XDL_CLR(opt, NEED_MINIMAL);
3930 opt->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3931 opt->xdl_opts |= value;
3932 }
3933 else if (!strcmp(s, "ignore-space-change"))
3934 DIFF_XDL_SET(opt, IGNORE_WHITESPACE_CHANGE);
3935 else if (!strcmp(s, "ignore-all-space"))
3936 DIFF_XDL_SET(opt, IGNORE_WHITESPACE);
3937 else if (!strcmp(s, "ignore-space-at-eol"))
3938 DIFF_XDL_SET(opt, IGNORE_WHITESPACE_AT_EOL);
3939 else if (!strcmp(s, "ignore-cr-at-eol"))
3940 DIFF_XDL_SET(opt, IGNORE_CR_AT_EOL);
3941 else if (!strcmp(s, "renormalize"))
3942 opt->renormalize = 1;
3943 else if (!strcmp(s, "no-renormalize"))
3944 opt->renormalize = 0;
3945 else if (!strcmp(s, "no-renames"))
3946 opt->detect_renames = 0;
3947 else if (!strcmp(s, "find-renames")) {
3948 opt->detect_renames = 1;
3949 opt->rename_score = 0;
3950 }
3951 else if (skip_prefix(s, "find-renames=", &arg) ||
3952 skip_prefix(s, "rename-threshold=", &arg)) {
3953 if ((opt->rename_score = parse_rename_score(&arg)) == -1 || *arg != 0)
3954 return -1;
3955 opt->detect_renames = 1;
3956 }
3957 /*
3958 * Please update $__git_merge_strategy_options in
3959 * git-completion.bash when you add new options
3960 */
3961 else
3962 return -1;
3963 return 0;
3964 }