1#include <signal.h>
2#include <sys/time.h>
3#include "cache.h"
4#include "dir.h"
5#include "tree.h"
6#include "tree-walk.h"
7#include "cache-tree.h"
8#include "unpack-trees.h"
9
10#define DBRT_DEBUG 1
11
12struct tree_entry_list {
13 struct tree_entry_list *next;
14 unsigned directory : 1;
15 unsigned executable : 1;
16 unsigned symlink : 1;
17 unsigned int mode;
18 const char *name;
19 const unsigned char *sha1;
20};
21
22static struct tree_entry_list *create_tree_entry_list(struct tree *tree)
23{
24 struct tree_desc desc;
25 struct name_entry one;
26 struct tree_entry_list *ret = NULL;
27 struct tree_entry_list **list_p = &ret;
28
29 if (!tree->object.parsed)
30 parse_tree(tree);
31
32 desc.buf = tree->buffer;
33 desc.size = tree->size;
34
35 while (tree_entry(&desc, &one)) {
36 struct tree_entry_list *entry;
37
38 entry = xmalloc(sizeof(struct tree_entry_list));
39 entry->name = one.path;
40 entry->sha1 = one.sha1;
41 entry->mode = one.mode;
42 entry->directory = S_ISDIR(one.mode) != 0;
43 entry->executable = (one.mode & S_IXUSR) != 0;
44 entry->symlink = S_ISLNK(one.mode) != 0;
45 entry->next = NULL;
46
47 *list_p = entry;
48 list_p = &entry->next;
49 }
50 return ret;
51}
52
53static int entcmp(const char *name1, int dir1, const char *name2, int dir2)
54{
55 int len1 = strlen(name1);
56 int len2 = strlen(name2);
57 int len = len1 < len2 ? len1 : len2;
58 int ret = memcmp(name1, name2, len);
59 unsigned char c1, c2;
60 if (ret)
61 return ret;
62 c1 = name1[len];
63 c2 = name2[len];
64 if (!c1 && dir1)
65 c1 = '/';
66 if (!c2 && dir2)
67 c2 = '/';
68 ret = (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
69 if (c1 && c2 && !ret)
70 ret = len1 - len2;
71 return ret;
72}
73
74static int unpack_trees_rec(struct tree_entry_list **posns, int len,
75 const char *base, struct unpack_trees_options *o,
76 int *indpos,
77 struct tree_entry_list *df_conflict_list)
78{
79 int baselen = strlen(base);
80 int src_size = len + 1;
81 int i_stk = i_stk;
82 int retval = 0;
83
84 if (o->dir)
85 i_stk = push_exclude_per_directory(o->dir, base, strlen(base));
86
87 do {
88 int i;
89 const char *first;
90 int firstdir = 0;
91 int pathlen;
92 unsigned ce_size;
93 struct tree_entry_list **subposns;
94 struct cache_entry **src;
95 int any_files = 0;
96 int any_dirs = 0;
97 char *cache_name;
98 int ce_stage;
99
100 /* Find the first name in the input. */
101
102 first = NULL;
103 cache_name = NULL;
104
105 /* Check the cache */
106 if (o->merge && *indpos < active_nr) {
107 /* This is a bit tricky: */
108 /* If the index has a subdirectory (with
109 * contents) as the first name, it'll get a
110 * filename like "foo/bar". But that's after
111 * "foo", so the entry in trees will get
112 * handled first, at which point we'll go into
113 * "foo", and deal with "bar" from the index,
114 * because the base will be "foo/". The only
115 * way we can actually have "foo/bar" first of
116 * all the things is if the trees don't
117 * contain "foo" at all, in which case we'll
118 * handle "foo/bar" without going into the
119 * directory, but that's fine (and will return
120 * an error anyway, with the added unknown
121 * file case.
122 */
123
124 cache_name = active_cache[*indpos]->name;
125 if (strlen(cache_name) > baselen &&
126 !memcmp(cache_name, base, baselen)) {
127 cache_name += baselen;
128 first = cache_name;
129 } else {
130 cache_name = NULL;
131 }
132 }
133
134#if DBRT_DEBUG > 1
135 if (first)
136 printf("index %s\n", first);
137#endif
138 for (i = 0; i < len; i++) {
139 if (!posns[i] || posns[i] == df_conflict_list)
140 continue;
141#if DBRT_DEBUG > 1
142 printf("%d %s\n", i + 1, posns[i]->name);
143#endif
144 if (!first || entcmp(first, firstdir,
145 posns[i]->name,
146 posns[i]->directory) > 0) {
147 first = posns[i]->name;
148 firstdir = posns[i]->directory;
149 }
150 }
151 /* No name means we're done */
152 if (!first)
153 goto leave_directory;
154
155 pathlen = strlen(first);
156 ce_size = cache_entry_size(baselen + pathlen);
157
158 src = xcalloc(src_size, sizeof(struct cache_entry *));
159
160 subposns = xcalloc(len, sizeof(struct tree_list_entry *));
161
162 if (cache_name && !strcmp(cache_name, first)) {
163 any_files = 1;
164 src[0] = active_cache[*indpos];
165 remove_cache_entry_at(*indpos);
166 }
167
168 for (i = 0; i < len; i++) {
169 struct cache_entry *ce;
170
171 if (!posns[i] ||
172 (posns[i] != df_conflict_list &&
173 strcmp(first, posns[i]->name))) {
174 continue;
175 }
176
177 if (posns[i] == df_conflict_list) {
178 src[i + o->merge] = o->df_conflict_entry;
179 continue;
180 }
181
182 if (posns[i]->directory) {
183 struct tree *tree = lookup_tree(posns[i]->sha1);
184 any_dirs = 1;
185 parse_tree(tree);
186 subposns[i] = create_tree_entry_list(tree);
187 posns[i] = posns[i]->next;
188 src[i + o->merge] = o->df_conflict_entry;
189 continue;
190 }
191
192 if (!o->merge)
193 ce_stage = 0;
194 else if (i + 1 < o->head_idx)
195 ce_stage = 1;
196 else if (i + 1 > o->head_idx)
197 ce_stage = 3;
198 else
199 ce_stage = 2;
200
201 ce = xcalloc(1, ce_size);
202 ce->ce_mode = create_ce_mode(posns[i]->mode);
203 ce->ce_flags = create_ce_flags(baselen + pathlen,
204 ce_stage);
205 memcpy(ce->name, base, baselen);
206 memcpy(ce->name + baselen, first, pathlen + 1);
207
208 any_files = 1;
209
210 hashcpy(ce->sha1, posns[i]->sha1);
211 src[i + o->merge] = ce;
212 subposns[i] = df_conflict_list;
213 posns[i] = posns[i]->next;
214 }
215 if (any_files) {
216 if (o->merge) {
217 int ret;
218
219#if DBRT_DEBUG > 1
220 printf("%s:\n", first);
221 for (i = 0; i < src_size; i++) {
222 printf(" %d ", i);
223 if (src[i])
224 printf("%s\n", sha1_to_hex(src[i]->sha1));
225 else
226 printf("\n");
227 }
228#endif
229 ret = o->fn(src, o);
230
231#if DBRT_DEBUG > 1
232 printf("Added %d entries\n", ret);
233#endif
234 *indpos += ret;
235 } else {
236 for (i = 0; i < src_size; i++) {
237 if (src[i]) {
238 add_cache_entry(src[i], ADD_CACHE_OK_TO_ADD|ADD_CACHE_SKIP_DFCHECK);
239 }
240 }
241 }
242 }
243 if (any_dirs) {
244 char *newbase = xmalloc(baselen + 2 + pathlen);
245 memcpy(newbase, base, baselen);
246 memcpy(newbase + baselen, first, pathlen);
247 newbase[baselen + pathlen] = '/';
248 newbase[baselen + pathlen + 1] = '\0';
249 if (unpack_trees_rec(subposns, len, newbase, o,
250 indpos, df_conflict_list)) {
251 retval = -1;
252 goto leave_directory;
253 }
254 free(newbase);
255 }
256 free(subposns);
257 free(src);
258 } while (1);
259
260 leave_directory:
261 if (o->dir)
262 pop_exclude_per_directory(o->dir, i_stk);
263 return retval;
264}
265
266/* Unlink the last component and attempt to remove leading
267 * directories, in case this unlink is the removal of the
268 * last entry in the directory -- empty directories are removed.
269 */
270static void unlink_entry(char *name)
271{
272 char *cp, *prev;
273
274 if (unlink(name))
275 return;
276 prev = NULL;
277 while (1) {
278 int status;
279 cp = strrchr(name, '/');
280 if (prev)
281 *prev = '/';
282 if (!cp)
283 break;
284
285 *cp = 0;
286 status = rmdir(name);
287 if (status) {
288 *cp = '/';
289 break;
290 }
291 prev = cp;
292 }
293}
294
295static volatile sig_atomic_t progress_update;
296
297static void progress_interval(int signum)
298{
299 progress_update = 1;
300}
301
302static void setup_progress_signal(void)
303{
304 struct sigaction sa;
305 struct itimerval v;
306
307 memset(&sa, 0, sizeof(sa));
308 sa.sa_handler = progress_interval;
309 sigemptyset(&sa.sa_mask);
310 sa.sa_flags = SA_RESTART;
311 sigaction(SIGALRM, &sa, NULL);
312
313 v.it_interval.tv_sec = 1;
314 v.it_interval.tv_usec = 0;
315 v.it_value = v.it_interval;
316 setitimer(ITIMER_REAL, &v, NULL);
317}
318
319static struct checkout state;
320static void check_updates(struct cache_entry **src, int nr,
321 struct unpack_trees_options *o)
322{
323 unsigned short mask = htons(CE_UPDATE);
324 unsigned last_percent = 200, cnt = 0, total = 0;
325
326 if (o->update && o->verbose_update) {
327 for (total = cnt = 0; cnt < nr; cnt++) {
328 struct cache_entry *ce = src[cnt];
329 if (!ce->ce_mode || ce->ce_flags & mask)
330 total++;
331 }
332
333 /* Don't bother doing this for very small updates */
334 if (total < 250)
335 total = 0;
336
337 if (total) {
338 fprintf(stderr, "Checking files out...\n");
339 setup_progress_signal();
340 progress_update = 1;
341 }
342 cnt = 0;
343 }
344
345 while (nr--) {
346 struct cache_entry *ce = *src++;
347
348 if (total) {
349 if (!ce->ce_mode || ce->ce_flags & mask) {
350 unsigned percent;
351 cnt++;
352 percent = (cnt * 100) / total;
353 if (percent != last_percent ||
354 progress_update) {
355 fprintf(stderr, "%4u%% (%u/%u) done\r",
356 percent, cnt, total);
357 last_percent = percent;
358 progress_update = 0;
359 }
360 }
361 }
362 if (!ce->ce_mode) {
363 if (o->update)
364 unlink_entry(ce->name);
365 continue;
366 }
367 if (ce->ce_flags & mask) {
368 ce->ce_flags &= ~mask;
369 if (o->update)
370 checkout_entry(ce, &state, NULL);
371 }
372 }
373 if (total) {
374 signal(SIGALRM, SIG_IGN);
375 fputc('\n', stderr);
376 }
377}
378
379int unpack_trees(struct object_list *trees, struct unpack_trees_options *o)
380{
381 int indpos = 0;
382 unsigned len = object_list_length(trees);
383 struct tree_entry_list **posns;
384 int i;
385 struct object_list *posn = trees;
386 struct tree_entry_list df_conflict_list;
387 struct cache_entry df_conflict_entry;
388
389 memset(&df_conflict_list, 0, sizeof(df_conflict_list));
390 df_conflict_list.next = &df_conflict_list;
391 memset(&state, 0, sizeof(state));
392 state.base_dir = "";
393 state.force = 1;
394 state.quiet = 1;
395 state.refresh_cache = 1;
396
397 o->merge_size = len;
398 memset(&df_conflict_entry, 0, sizeof(df_conflict_entry));
399 o->df_conflict_entry = &df_conflict_entry;
400
401 if (len) {
402 posns = xmalloc(len * sizeof(struct tree_entry_list *));
403 for (i = 0; i < len; i++) {
404 posns[i] = create_tree_entry_list((struct tree *) posn->item);
405 posn = posn->next;
406 }
407 if (unpack_trees_rec(posns, len, o->prefix ? o->prefix : "",
408 o, &indpos, &df_conflict_list))
409 return -1;
410 }
411
412 if (o->trivial_merges_only && o->nontrivial_merge)
413 die("Merge requires file-level merging");
414
415 check_updates(active_cache, active_nr, o);
416 return 0;
417}
418
419/* Here come the merge functions */
420
421static void reject_merge(struct cache_entry *ce)
422{
423 die("Entry '%s' would be overwritten by merge. Cannot merge.",
424 ce->name);
425}
426
427static int same(struct cache_entry *a, struct cache_entry *b)
428{
429 if (!!a != !!b)
430 return 0;
431 if (!a && !b)
432 return 1;
433 return a->ce_mode == b->ce_mode &&
434 !hashcmp(a->sha1, b->sha1);
435}
436
437
438/*
439 * When a CE gets turned into an unmerged entry, we
440 * want it to be up-to-date
441 */
442static void verify_uptodate(struct cache_entry *ce,
443 struct unpack_trees_options *o)
444{
445 struct stat st;
446
447 if (o->index_only || o->reset)
448 return;
449
450 if (!lstat(ce->name, &st)) {
451 unsigned changed = ce_match_stat(ce, &st, 1);
452 if (!changed)
453 return;
454 errno = 0;
455 }
456 if (o->reset) {
457 ce->ce_flags |= htons(CE_UPDATE);
458 return;
459 }
460 if (errno == ENOENT)
461 return;
462 die("Entry '%s' not uptodate. Cannot merge.", ce->name);
463}
464
465static void invalidate_ce_path(struct cache_entry *ce)
466{
467 if (ce)
468 cache_tree_invalidate_path(active_cache_tree, ce->name);
469}
470
471/*
472 * We do not want to remove or overwrite a working tree file that
473 * is not tracked, unless it is ignored.
474 */
475static void verify_absent(const char *path, const char *action,
476 struct unpack_trees_options *o)
477{
478 struct stat st;
479
480 if (o->index_only || o->reset || !o->update)
481 return;
482 if (!lstat(path, &st) && !(o->dir && excluded(o->dir, path)))
483 die("Untracked working tree file '%s' "
484 "would be %s by merge.", path, action);
485}
486
487static int merged_entry(struct cache_entry *merge, struct cache_entry *old,
488 struct unpack_trees_options *o)
489{
490 merge->ce_flags |= htons(CE_UPDATE);
491 if (old) {
492 /*
493 * See if we can re-use the old CE directly?
494 * That way we get the uptodate stat info.
495 *
496 * This also removes the UPDATE flag on
497 * a match.
498 */
499 if (same(old, merge)) {
500 *merge = *old;
501 } else {
502 verify_uptodate(old, o);
503 invalidate_ce_path(old);
504 }
505 }
506 else {
507 verify_absent(merge->name, "overwritten", o);
508 invalidate_ce_path(merge);
509 }
510
511 merge->ce_flags &= ~htons(CE_STAGEMASK);
512 add_cache_entry(merge, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
513 return 1;
514}
515
516static int deleted_entry(struct cache_entry *ce, struct cache_entry *old,
517 struct unpack_trees_options *o)
518{
519 if (old)
520 verify_uptodate(old, o);
521 else
522 verify_absent(ce->name, "removed", o);
523 ce->ce_mode = 0;
524 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
525 invalidate_ce_path(ce);
526 return 1;
527}
528
529static int keep_entry(struct cache_entry *ce)
530{
531 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD);
532 return 1;
533}
534
535#if DBRT_DEBUG
536static void show_stage_entry(FILE *o,
537 const char *label, const struct cache_entry *ce)
538{
539 if (!ce)
540 fprintf(o, "%s (missing)\n", label);
541 else
542 fprintf(o, "%s%06o %s %d\t%s\n",
543 label,
544 ntohl(ce->ce_mode),
545 sha1_to_hex(ce->sha1),
546 ce_stage(ce),
547 ce->name);
548}
549#endif
550
551int threeway_merge(struct cache_entry **stages,
552 struct unpack_trees_options *o)
553{
554 struct cache_entry *index;
555 struct cache_entry *head;
556 struct cache_entry *remote = stages[o->head_idx + 1];
557 int count;
558 int head_match = 0;
559 int remote_match = 0;
560 const char *path = NULL;
561
562 int df_conflict_head = 0;
563 int df_conflict_remote = 0;
564
565 int any_anc_missing = 0;
566 int no_anc_exists = 1;
567 int i;
568
569 for (i = 1; i < o->head_idx; i++) {
570 if (!stages[i])
571 any_anc_missing = 1;
572 else {
573 if (!path)
574 path = stages[i]->name;
575 no_anc_exists = 0;
576 }
577 }
578
579 index = stages[0];
580 head = stages[o->head_idx];
581
582 if (head == o->df_conflict_entry) {
583 df_conflict_head = 1;
584 head = NULL;
585 }
586
587 if (remote == o->df_conflict_entry) {
588 df_conflict_remote = 1;
589 remote = NULL;
590 }
591
592 if (!path && index)
593 path = index->name;
594 if (!path && head)
595 path = head->name;
596 if (!path && remote)
597 path = remote->name;
598
599 /* First, if there's a #16 situation, note that to prevent #13
600 * and #14.
601 */
602 if (!same(remote, head)) {
603 for (i = 1; i < o->head_idx; i++) {
604 if (same(stages[i], head)) {
605 head_match = i;
606 }
607 if (same(stages[i], remote)) {
608 remote_match = i;
609 }
610 }
611 }
612
613 /* We start with cases where the index is allowed to match
614 * something other than the head: #14(ALT) and #2ALT, where it
615 * is permitted to match the result instead.
616 */
617 /* #14, #14ALT, #2ALT */
618 if (remote && !df_conflict_head && head_match && !remote_match) {
619 if (index && !same(index, remote) && !same(index, head))
620 reject_merge(index);
621 return merged_entry(remote, index, o);
622 }
623 /*
624 * If we have an entry in the index cache, then we want to
625 * make sure that it matches head.
626 */
627 if (index && !same(index, head)) {
628 reject_merge(index);
629 }
630
631 if (head) {
632 /* #5ALT, #15 */
633 if (same(head, remote))
634 return merged_entry(head, index, o);
635 /* #13, #3ALT */
636 if (!df_conflict_remote && remote_match && !head_match)
637 return merged_entry(head, index, o);
638 }
639
640 /* #1 */
641 if (!head && !remote && any_anc_missing)
642 return 0;
643
644 /* Under the new "aggressive" rule, we resolve mostly trivial
645 * cases that we historically had git-merge-one-file resolve.
646 */
647 if (o->aggressive) {
648 int head_deleted = !head && !df_conflict_head;
649 int remote_deleted = !remote && !df_conflict_remote;
650 /*
651 * Deleted in both.
652 * Deleted in one and unchanged in the other.
653 */
654 if ((head_deleted && remote_deleted) ||
655 (head_deleted && remote && remote_match) ||
656 (remote_deleted && head && head_match)) {
657 if (index)
658 return deleted_entry(index, index, o);
659 else if (path && !head_deleted)
660 verify_absent(path, "removed", o);
661 return 0;
662 }
663 /*
664 * Added in both, identically.
665 */
666 if (no_anc_exists && head && remote && same(head, remote))
667 return merged_entry(head, index, o);
668
669 }
670
671 /* Below are "no merge" cases, which require that the index be
672 * up-to-date to avoid the files getting overwritten with
673 * conflict resolution files.
674 */
675 if (index) {
676 verify_uptodate(index, o);
677 }
678
679 o->nontrivial_merge = 1;
680
681 /* #2, #3, #4, #6, #7, #9, #11. */
682 count = 0;
683 if (!head_match || !remote_match) {
684 for (i = 1; i < o->head_idx; i++) {
685 if (stages[i]) {
686 keep_entry(stages[i]);
687 count++;
688 break;
689 }
690 }
691 }
692#if DBRT_DEBUG
693 else {
694 fprintf(stderr, "read-tree: warning #16 detected\n");
695 show_stage_entry(stderr, "head ", stages[head_match]);
696 show_stage_entry(stderr, "remote ", stages[remote_match]);
697 }
698#endif
699 if (head) { count += keep_entry(head); }
700 if (remote) { count += keep_entry(remote); }
701 return count;
702}
703
704/*
705 * Two-way merge.
706 *
707 * The rule is to "carry forward" what is in the index without losing
708 * information across a "fast forward", favoring a successful merge
709 * over a merge failure when it makes sense. For details of the
710 * "carry forward" rule, please see <Documentation/git-read-tree.txt>.
711 *
712 */
713int twoway_merge(struct cache_entry **src,
714 struct unpack_trees_options *o)
715{
716 struct cache_entry *current = src[0];
717 struct cache_entry *oldtree = src[1], *newtree = src[2];
718
719 if (o->merge_size != 2)
720 return error("Cannot do a twoway merge of %d trees",
721 o->merge_size);
722
723 if (current) {
724 if ((!oldtree && !newtree) || /* 4 and 5 */
725 (!oldtree && newtree &&
726 same(current, newtree)) || /* 6 and 7 */
727 (oldtree && newtree &&
728 same(oldtree, newtree)) || /* 14 and 15 */
729 (oldtree && newtree &&
730 !same(oldtree, newtree) && /* 18 and 19*/
731 same(current, newtree))) {
732 return keep_entry(current);
733 }
734 else if (oldtree && !newtree && same(current, oldtree)) {
735 /* 10 or 11 */
736 return deleted_entry(oldtree, current, o);
737 }
738 else if (oldtree && newtree &&
739 same(current, oldtree) && !same(current, newtree)) {
740 /* 20 or 21 */
741 return merged_entry(newtree, current, o);
742 }
743 else {
744 /* all other failures */
745 if (oldtree)
746 reject_merge(oldtree);
747 if (current)
748 reject_merge(current);
749 if (newtree)
750 reject_merge(newtree);
751 return -1;
752 }
753 }
754 else if (newtree)
755 return merged_entry(newtree, current, o);
756 else
757 return deleted_entry(oldtree, current, o);
758}
759
760/*
761 * Bind merge.
762 *
763 * Keep the index entries at stage0, collapse stage1 but make sure
764 * stage0 does not have anything there.
765 */
766int bind_merge(struct cache_entry **src,
767 struct unpack_trees_options *o)
768{
769 struct cache_entry *old = src[0];
770 struct cache_entry *a = src[1];
771
772 if (o->merge_size != 1)
773 return error("Cannot do a bind merge of %d trees\n",
774 o->merge_size);
775 if (a && old)
776 die("Entry '%s' overlaps. Cannot bind.", a->name);
777 if (!a)
778 return keep_entry(old);
779 else
780 return merged_entry(a, NULL, o);
781}
782
783/*
784 * One-way merge.
785 *
786 * The rule is:
787 * - take the stat information from stage0, take the data from stage1
788 */
789int oneway_merge(struct cache_entry **src,
790 struct unpack_trees_options *o)
791{
792 struct cache_entry *old = src[0];
793 struct cache_entry *a = src[1];
794
795 if (o->merge_size != 1)
796 return error("Cannot do a oneway merge of %d trees",
797 o->merge_size);
798
799 if (!a)
800 return deleted_entry(old, old, o);
801 if (old && same(old, a)) {
802 if (o->reset) {
803 struct stat st;
804 if (lstat(old->name, &st) ||
805 ce_match_stat(old, &st, 1))
806 old->ce_flags |= htons(CE_UPDATE);
807 }
808 return keep_entry(old);
809 }
810 return merged_entry(a, old, o);
811}