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