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