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