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