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