4 * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
6 * Based on git-merge.sh by Junio C Hamano.
10 #include "parse-options.h"
12 #include "run-command.h"
18 #include "unpack-trees.h"
19 #include "cache-tree.h"
26 #include "merge-recursive.h"
28 #define DEFAULT_TWOHEAD (1<<0)
29 #define DEFAULT_OCTOPUS (1<<1)
30 #define NO_FAST_FORWARD (1<<2)
31 #define NO_TRIVIAL (1<<3)
38 static const char * const builtin_merge_usage
[] = {
39 "git merge [options] <remote>...",
40 "git merge [options] <msg> HEAD <remote>",
44 static int show_diffstat
= 1, option_log
, squash
;
45 static int option_commit
= 1, allow_fast_forward
= 1;
46 static int fast_forward_only
;
47 static int allow_trivial
= 1, have_message
;
48 static struct strbuf merge_msg
;
49 static struct commit_list
*remoteheads
;
50 static unsigned char head
[20], stash
[20];
51 static struct strategy
**use_strategies
;
52 static size_t use_strategies_nr
, use_strategies_alloc
;
53 static const char **xopts
;
54 static size_t xopts_nr
, xopts_alloc
;
55 static const char *branch
;
58 static struct strategy all_strategy
[] = {
59 { "recursive", DEFAULT_TWOHEAD
| NO_TRIVIAL
},
60 { "octopus", DEFAULT_OCTOPUS
},
62 { "ours", NO_FAST_FORWARD
| NO_TRIVIAL
},
63 { "subtree", NO_FAST_FORWARD
| NO_TRIVIAL
},
66 static const char *pull_twohead
, *pull_octopus
;
68 static int option_parse_message(const struct option
*opt
,
69 const char *arg
, int unset
)
71 struct strbuf
*buf
= opt
->value
;
74 strbuf_setlen(buf
, 0);
76 strbuf_addf(buf
, "%s\n\n", arg
);
79 return error("switch `m' requires a value");
83 static struct strategy
*get_strategy(const char *name
)
87 static struct cmdnames main_cmds
, other_cmds
;
93 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
94 if (!strcmp(name
, all_strategy
[i
].name
))
95 return &all_strategy
[i
];
98 struct cmdnames not_strategies
;
101 memset(¬_strategies
, 0, sizeof(struct cmdnames
));
102 load_command_list("git-merge-", &main_cmds
, &other_cmds
);
103 for (i
= 0; i
< main_cmds
.cnt
; i
++) {
105 struct cmdname
*ent
= main_cmds
.names
[i
];
106 for (j
= 0; j
< ARRAY_SIZE(all_strategy
); j
++)
107 if (!strncmp(ent
->name
, all_strategy
[j
].name
, ent
->len
)
108 && !all_strategy
[j
].name
[ent
->len
])
111 add_cmdname(¬_strategies
, ent
->name
, ent
->len
);
113 exclude_cmds(&main_cmds
, ¬_strategies
);
115 if (!is_in_cmdlist(&main_cmds
, name
) && !is_in_cmdlist(&other_cmds
, name
)) {
116 fprintf(stderr
, "Could not find merge strategy '%s'.\n", name
);
117 fprintf(stderr
, "Available strategies are:");
118 for (i
= 0; i
< main_cmds
.cnt
; i
++)
119 fprintf(stderr
, " %s", main_cmds
.names
[i
]->name
);
120 fprintf(stderr
, ".\n");
121 if (other_cmds
.cnt
) {
122 fprintf(stderr
, "Available custom strategies are:");
123 for (i
= 0; i
< other_cmds
.cnt
; i
++)
124 fprintf(stderr
, " %s", other_cmds
.names
[i
]->name
);
125 fprintf(stderr
, ".\n");
130 ret
= xcalloc(1, sizeof(struct strategy
));
131 ret
->name
= xstrdup(name
);
135 static void append_strategy(struct strategy
*s
)
137 ALLOC_GROW(use_strategies
, use_strategies_nr
+ 1, use_strategies_alloc
);
138 use_strategies
[use_strategies_nr
++] = s
;
141 static int option_parse_strategy(const struct option
*opt
,
142 const char *name
, int unset
)
147 append_strategy(get_strategy(name
));
151 static int option_parse_x(const struct option
*opt
,
152 const char *arg
, int unset
)
157 ALLOC_GROW(xopts
, xopts_nr
+ 1, xopts_alloc
);
158 xopts
[xopts_nr
++] = xstrdup(arg
);
162 static int option_parse_n(const struct option
*opt
,
163 const char *arg
, int unset
)
165 show_diffstat
= unset
;
169 static struct option builtin_merge_options
[] = {
170 { OPTION_CALLBACK
, 'n', NULL
, NULL
, NULL
,
171 "do not show a diffstat at the end of the merge",
172 PARSE_OPT_NOARG
, option_parse_n
},
173 OPT_BOOLEAN(0, "stat", &show_diffstat
,
174 "show a diffstat at the end of the merge"),
175 OPT_BOOLEAN(0, "summary", &show_diffstat
, "(synonym to --stat)"),
176 OPT_BOOLEAN(0, "log", &option_log
,
177 "add list of one-line log to merge commit message"),
178 OPT_BOOLEAN(0, "squash", &squash
,
179 "create a single commit instead of doing a merge"),
180 OPT_BOOLEAN(0, "commit", &option_commit
,
181 "perform a commit if the merge succeeds (default)"),
182 OPT_BOOLEAN(0, "ff", &allow_fast_forward
,
183 "allow fast-forward (default)"),
184 OPT_BOOLEAN(0, "ff-only", &fast_forward_only
,
185 "abort if fast-forward is not possible"),
186 OPT_CALLBACK('s', "strategy", &use_strategies
, "strategy",
187 "merge strategy to use", option_parse_strategy
),
188 OPT_CALLBACK('X', "strategy-option", &xopts
, "option=value",
189 "option for selected merge strategy", option_parse_x
),
190 OPT_CALLBACK('m', "message", &merge_msg
, "message",
191 "message to be used for the merge commit (if any)",
192 option_parse_message
),
193 OPT__VERBOSITY(&verbosity
),
197 /* Cleans up metadata that is uninteresting after a succeeded merge. */
198 static void drop_save(void)
200 unlink(git_path("MERGE_HEAD"));
201 unlink(git_path("MERGE_MSG"));
202 unlink(git_path("MERGE_MODE"));
205 static void save_state(void)
208 struct child_process cp
;
209 struct strbuf buffer
= STRBUF_INIT
;
210 const char *argv
[] = {"stash", "create", NULL
};
212 memset(&cp
, 0, sizeof(cp
));
217 if (start_command(&cp
))
218 die("could not run stash.");
219 len
= strbuf_read(&buffer
, cp
.out
, 1024);
222 if (finish_command(&cp
) || len
< 0)
226 strbuf_setlen(&buffer
, buffer
.len
-1);
227 if (get_sha1(buffer
.buf
, stash
))
228 die("not a valid object: %s", buffer
.buf
);
231 static void reset_hard(unsigned const char *sha1
, int verbose
)
236 args
[i
++] = "read-tree";
239 args
[i
++] = "--reset";
241 args
[i
++] = sha1_to_hex(sha1
);
244 if (run_command_v_opt(args
, RUN_GIT_CMD
))
245 die("read-tree failed");
248 static void restore_state(void)
250 struct strbuf sb
= STRBUF_INIT
;
251 const char *args
[] = { "stash", "apply", NULL
, NULL
};
253 if (is_null_sha1(stash
))
258 args
[2] = sha1_to_hex(stash
);
261 * It is OK to ignore error here, for example when there was
262 * nothing to restore.
264 run_command_v_opt(args
, RUN_GIT_CMD
);
267 refresh_cache(REFRESH_QUIET
);
270 /* This is called when no merge was necessary. */
271 static void finish_up_to_date(const char *msg
)
274 printf("%s%s\n", squash
? " (nothing to squash)" : "", msg
);
278 static void squash_message(void)
281 struct commit
*commit
;
282 struct strbuf out
= STRBUF_INIT
;
283 struct commit_list
*j
;
285 struct pretty_print_context ctx
= {0};
287 printf("Squash commit -- not updating HEAD\n");
288 fd
= open(git_path("SQUASH_MSG"), O_WRONLY
| O_CREAT
, 0666);
290 die_errno("Could not write to '%s'", git_path("SQUASH_MSG"));
292 init_revisions(&rev
, NULL
);
293 rev
.ignore_merges
= 1;
294 rev
.commit_format
= CMIT_FMT_MEDIUM
;
296 commit
= lookup_commit(head
);
297 commit
->object
.flags
|= UNINTERESTING
;
298 add_pending_object(&rev
, &commit
->object
, NULL
);
300 for (j
= remoteheads
; j
; j
= j
->next
)
301 add_pending_object(&rev
, &j
->item
->object
, NULL
);
303 setup_revisions(0, NULL
, &rev
, NULL
);
304 if (prepare_revision_walk(&rev
))
305 die("revision walk setup failed");
307 ctx
.abbrev
= rev
.abbrev
;
308 ctx
.date_mode
= rev
.date_mode
;
310 strbuf_addstr(&out
, "Squashed commit of the following:\n");
311 while ((commit
= get_revision(&rev
)) != NULL
) {
312 strbuf_addch(&out
, '\n');
313 strbuf_addf(&out
, "commit %s\n",
314 sha1_to_hex(commit
->object
.sha1
));
315 pretty_print_commit(rev
.commit_format
, commit
, &out
, &ctx
);
317 if (write(fd
, out
.buf
, out
.len
) < 0)
318 die_errno("Writing SQUASH_MSG");
320 die_errno("Finishing SQUASH_MSG");
321 strbuf_release(&out
);
324 static void finish(const unsigned char *new_head
, const char *msg
)
326 struct strbuf reflog_message
= STRBUF_INIT
;
329 strbuf_addstr(&reflog_message
, getenv("GIT_REFLOG_ACTION"));
333 strbuf_addf(&reflog_message
, "%s: %s",
334 getenv("GIT_REFLOG_ACTION"), msg
);
339 if (verbosity
>= 0 && !merge_msg
.len
)
340 printf("No merge message -- not updating HEAD\n");
342 const char *argv_gc_auto
[] = { "gc", "--auto", NULL
};
343 update_ref(reflog_message
.buf
, "HEAD",
347 * We ignore errors in 'gc --auto', since the
348 * user should see them.
350 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
353 if (new_head
&& show_diffstat
) {
354 struct diff_options opts
;
356 opts
.output_format
|=
357 DIFF_FORMAT_SUMMARY
| DIFF_FORMAT_DIFFSTAT
;
358 opts
.detect_rename
= DIFF_DETECT_RENAME
;
359 if (diff_use_color_default
> 0)
360 DIFF_OPT_SET(&opts
, COLOR_DIFF
);
361 if (diff_setup_done(&opts
) < 0)
362 die("diff_setup_done failed");
363 diff_tree_sha1(head
, new_head
, "", &opts
);
368 /* Run a post-merge hook */
369 run_hook(NULL
, "post-merge", squash
? "1" : "0", NULL
);
371 strbuf_release(&reflog_message
);
374 /* Get the name for the merge commit's message. */
375 static void merge_name(const char *remote
, struct strbuf
*msg
)
377 struct object
*remote_head
;
378 unsigned char branch_head
[20], buf_sha
[20];
379 struct strbuf buf
= STRBUF_INIT
;
380 struct strbuf bname
= STRBUF_INIT
;
385 strbuf_branchname(&bname
, remote
);
388 memset(branch_head
, 0, sizeof(branch_head
));
389 remote_head
= peel_to_type(remote
, 0, NULL
, OBJ_COMMIT
);
391 die("'%s' does not point to a commit", remote
);
393 if (dwim_ref(remote
, strlen(remote
), branch_head
, &found_ref
) > 0) {
394 if (!prefixcmp(found_ref
, "refs/heads/")) {
395 strbuf_addf(msg
, "%s\t\tbranch '%s' of .\n",
396 sha1_to_hex(branch_head
), remote
);
399 if (!prefixcmp(found_ref
, "refs/remotes/")) {
400 strbuf_addf(msg
, "%s\t\tremote branch '%s' of .\n",
401 sha1_to_hex(branch_head
), remote
);
406 /* See if remote matches <name>^^^.. or <name>~<number> */
407 for (len
= 0, ptr
= remote
+ strlen(remote
);
408 remote
< ptr
&& ptr
[-1] == '^';
415 ptr
= strrchr(remote
, '~');
417 int seen_nonzero
= 0;
420 while (*++ptr
&& isdigit(*ptr
)) {
421 seen_nonzero
|= (*ptr
!= '0');
425 len
= 0; /* not ...~<number> */
426 else if (seen_nonzero
)
429 early
= 1; /* "name~" is "name~1"! */
433 struct strbuf truname
= STRBUF_INIT
;
434 strbuf_addstr(&truname
, "refs/heads/");
435 strbuf_addstr(&truname
, remote
);
436 strbuf_setlen(&truname
, truname
.len
- len
);
437 if (resolve_ref(truname
.buf
, buf_sha
, 0, NULL
)) {
439 "%s\t\tbranch '%s'%s of .\n",
440 sha1_to_hex(remote_head
->sha1
),
442 (early
? " (early part)" : ""));
443 strbuf_release(&truname
);
448 if (!strcmp(remote
, "FETCH_HEAD") &&
449 !access(git_path("FETCH_HEAD"), R_OK
)) {
451 struct strbuf line
= STRBUF_INIT
;
454 fp
= fopen(git_path("FETCH_HEAD"), "r");
456 die_errno("could not open '%s' for reading",
457 git_path("FETCH_HEAD"));
458 strbuf_getline(&line
, fp
, '\n');
460 ptr
= strstr(line
.buf
, "\tnot-for-merge\t");
462 strbuf_remove(&line
, ptr
-line
.buf
+1, 13);
463 strbuf_addbuf(msg
, &line
);
464 strbuf_release(&line
);
467 strbuf_addf(msg
, "%s\t\tcommit '%s'\n",
468 sha1_to_hex(remote_head
->sha1
), remote
);
470 strbuf_release(&buf
);
471 strbuf_release(&bname
);
474 static int git_merge_config(const char *k
, const char *v
, void *cb
)
476 if (branch
&& !prefixcmp(k
, "branch.") &&
477 !prefixcmp(k
+ 7, branch
) &&
478 !strcmp(k
+ 7 + strlen(branch
), ".mergeoptions")) {
484 argc
= split_cmdline(buf
, &argv
);
486 die("Bad branch.%s.mergeoptions string", branch
);
487 argv
= xrealloc(argv
, sizeof(*argv
) * (argc
+ 2));
488 memmove(argv
+ 1, argv
, sizeof(*argv
) * (argc
+ 1));
490 parse_options(argc
, argv
, NULL
, builtin_merge_options
,
491 builtin_merge_usage
, 0);
495 if (!strcmp(k
, "merge.diffstat") || !strcmp(k
, "merge.stat"))
496 show_diffstat
= git_config_bool(k
, v
);
497 else if (!strcmp(k
, "pull.twohead"))
498 return git_config_string(&pull_twohead
, k
, v
);
499 else if (!strcmp(k
, "pull.octopus"))
500 return git_config_string(&pull_octopus
, k
, v
);
501 else if (!strcmp(k
, "merge.log") || !strcmp(k
, "merge.summary"))
502 option_log
= git_config_bool(k
, v
);
503 return git_diff_ui_config(k
, v
, cb
);
506 static int read_tree_trivial(unsigned char *common
, unsigned char *head
,
510 struct tree
*trees
[MAX_UNPACK_TREES
];
511 struct tree_desc t
[MAX_UNPACK_TREES
];
512 struct unpack_trees_options opts
;
514 memset(&opts
, 0, sizeof(opts
));
516 opts
.src_index
= &the_index
;
517 opts
.dst_index
= &the_index
;
519 opts
.verbose_update
= 1;
520 opts
.trivial_merges_only
= 1;
522 trees
[nr_trees
] = parse_tree_indirect(common
);
523 if (!trees
[nr_trees
++])
525 trees
[nr_trees
] = parse_tree_indirect(head
);
526 if (!trees
[nr_trees
++])
528 trees
[nr_trees
] = parse_tree_indirect(one
);
529 if (!trees
[nr_trees
++])
531 opts
.fn
= threeway_merge
;
532 cache_tree_free(&active_cache_tree
);
533 for (i
= 0; i
< nr_trees
; i
++) {
534 parse_tree(trees
[i
]);
535 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
537 if (unpack_trees(nr_trees
, t
, &opts
))
542 static void write_tree_trivial(unsigned char *sha1
)
544 if (write_cache_as_tree(sha1
, 0, NULL
))
545 die("git write-tree failed to write a tree");
548 static int try_merge_strategy(const char *strategy
, struct commit_list
*common
,
549 const char *head_arg
)
552 int i
= 0, x
= 0, ret
;
553 struct commit_list
*j
;
554 struct strbuf buf
= STRBUF_INIT
;
556 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
558 index_fd
= hold_locked_index(lock
, 1);
559 refresh_cache(REFRESH_QUIET
);
560 if (active_cache_changed
&&
561 (write_cache(index_fd
, active_cache
, active_nr
) ||
562 commit_locked_index(lock
)))
563 return error("Unable to write index.");
564 rollback_lock_file(lock
);
566 if (!strcmp(strategy
, "recursive") || !strcmp(strategy
, "subtree")) {
568 struct commit
*result
;
569 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
571 struct commit_list
*reversed
= NULL
;
572 struct merge_options o
;
574 if (remoteheads
->next
) {
575 error("Not handling anything other than two heads merge.");
579 init_merge_options(&o
);
580 if (!strcmp(strategy
, "subtree"))
581 o
.subtree_shift
= "";
583 for (x
= 0; x
< xopts_nr
; x
++) {
584 if (!strcmp(xopts
[x
], "ours"))
585 o
.recursive_variant
= MERGE_RECURSIVE_OURS
;
586 else if (!strcmp(xopts
[x
], "theirs"))
587 o
.recursive_variant
= MERGE_RECURSIVE_THEIRS
;
588 else if (!strcmp(xopts
[x
], "subtree"))
589 o
.subtree_shift
= "";
590 else if (!prefixcmp(xopts
[x
], "subtree="))
591 o
.subtree_shift
= xopts
[x
]+8;
593 die("Unknown option for merge-recursive: -X%s", xopts
[x
]);
596 o
.branch1
= head_arg
;
597 o
.branch2
= remoteheads
->item
->util
;
599 for (j
= common
; j
; j
= j
->next
)
600 commit_list_insert(j
->item
, &reversed
);
602 index_fd
= hold_locked_index(lock
, 1);
603 clean
= merge_recursive(&o
, lookup_commit(head
),
604 remoteheads
->item
, reversed
, &result
);
605 if (active_cache_changed
&&
606 (write_cache(index_fd
, active_cache
, active_nr
) ||
607 commit_locked_index(lock
)))
608 die ("unable to write %s", get_index_file());
609 rollback_lock_file(lock
);
610 return clean
? 0 : 1;
612 args
= xmalloc((4 + xopts_nr
+ commit_list_count(common
) +
613 commit_list_count(remoteheads
)) * sizeof(char *));
614 strbuf_addf(&buf
, "merge-%s", strategy
);
616 for (x
= 0; x
< xopts_nr
; x
++) {
617 char *s
= xmalloc(strlen(xopts
[x
])+2+1);
619 strcpy(s
+2, xopts
[x
]);
622 for (j
= common
; j
; j
= j
->next
)
623 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
625 args
[i
++] = head_arg
;
626 for (j
= remoteheads
; j
; j
= j
->next
)
627 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
629 ret
= run_command_v_opt(args
, RUN_GIT_CMD
);
630 strbuf_release(&buf
);
632 for (x
= 0; x
< xopts_nr
; x
++)
633 free((void *)args
[i
++]);
634 for (j
= common
; j
; j
= j
->next
)
635 free((void *)args
[i
++]);
637 for (j
= remoteheads
; j
; j
= j
->next
)
638 free((void *)args
[i
++]);
641 if (read_cache() < 0)
642 die("failed to read the cache");
647 static void count_diff_files(struct diff_queue_struct
*q
,
648 struct diff_options
*opt
, void *data
)
655 static int count_unmerged_entries(void)
657 const struct index_state
*state
= &the_index
;
660 for (i
= 0; i
< state
->cache_nr
; i
++)
661 if (ce_stage(state
->cache
[i
]))
667 static int checkout_fast_forward(unsigned char *head
, unsigned char *remote
)
669 struct tree
*trees
[MAX_UNPACK_TREES
];
670 struct unpack_trees_options opts
;
671 struct tree_desc t
[MAX_UNPACK_TREES
];
672 int i
, fd
, nr_trees
= 0;
673 struct dir_struct dir
;
674 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
676 refresh_cache(REFRESH_QUIET
);
678 fd
= hold_locked_index(lock_file
, 1);
680 memset(&trees
, 0, sizeof(trees
));
681 memset(&opts
, 0, sizeof(opts
));
682 memset(&t
, 0, sizeof(t
));
683 memset(&dir
, 0, sizeof(dir
));
684 dir
.flags
|= DIR_SHOW_IGNORED
;
685 dir
.exclude_per_dir
= ".gitignore";
689 opts
.src_index
= &the_index
;
690 opts
.dst_index
= &the_index
;
692 opts
.verbose_update
= 1;
694 opts
.fn
= twoway_merge
;
696 trees
[nr_trees
] = parse_tree_indirect(head
);
697 if (!trees
[nr_trees
++])
699 trees
[nr_trees
] = parse_tree_indirect(remote
);
700 if (!trees
[nr_trees
++])
702 for (i
= 0; i
< nr_trees
; i
++) {
703 parse_tree(trees
[i
]);
704 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
706 if (unpack_trees(nr_trees
, t
, &opts
))
708 if (write_cache(fd
, active_cache
, active_nr
) ||
709 commit_locked_index(lock_file
))
710 die("unable to write new index file");
714 static void split_merge_strategies(const char *string
, struct strategy
**list
,
722 buf
= xstrdup(string
);
727 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
728 (*list
)[(*nr
)++].name
= xstrdup(q
);
733 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
734 (*list
)[(*nr
)++].name
= xstrdup(q
);
740 static void add_strategies(const char *string
, unsigned attr
)
742 struct strategy
*list
= NULL
;
743 int list_alloc
= 0, list_nr
= 0, i
;
745 memset(&list
, 0, sizeof(list
));
746 split_merge_strategies(string
, &list
, &list_nr
, &list_alloc
);
748 for (i
= 0; i
< list_nr
; i
++)
749 append_strategy(get_strategy(list
[i
].name
));
752 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
753 if (all_strategy
[i
].attr
& attr
)
754 append_strategy(&all_strategy
[i
]);
758 static int merge_trivial(void)
760 unsigned char result_tree
[20], result_commit
[20];
761 struct commit_list
*parent
= xmalloc(sizeof(*parent
));
763 write_tree_trivial(result_tree
);
764 printf("Wonderful.\n");
765 parent
->item
= lookup_commit(head
);
766 parent
->next
= xmalloc(sizeof(*parent
->next
));
767 parent
->next
->item
= remoteheads
->item
;
768 parent
->next
->next
= NULL
;
769 commit_tree(merge_msg
.buf
, result_tree
, parent
, result_commit
, NULL
);
770 finish(result_commit
, "In-index merge");
775 static int finish_automerge(struct commit_list
*common
,
776 unsigned char *result_tree
,
777 const char *wt_strategy
)
779 struct commit_list
*parents
= NULL
, *j
;
780 struct strbuf buf
= STRBUF_INIT
;
781 unsigned char result_commit
[20];
783 free_commit_list(common
);
784 if (allow_fast_forward
) {
785 parents
= remoteheads
;
786 commit_list_insert(lookup_commit(head
), &parents
);
787 parents
= reduce_heads(parents
);
789 struct commit_list
**pptr
= &parents
;
791 pptr
= &commit_list_insert(lookup_commit(head
),
793 for (j
= remoteheads
; j
; j
= j
->next
)
794 pptr
= &commit_list_insert(j
->item
, pptr
)->next
;
796 free_commit_list(remoteheads
);
797 strbuf_addch(&merge_msg
, '\n');
798 commit_tree(merge_msg
.buf
, result_tree
, parents
, result_commit
, NULL
);
799 strbuf_addf(&buf
, "Merge made by %s.", wt_strategy
);
800 finish(result_commit
, buf
.buf
);
801 strbuf_release(&buf
);
806 static int suggest_conflicts(void)
811 fp
= fopen(git_path("MERGE_MSG"), "a");
813 die_errno("Could not open '%s' for writing",
814 git_path("MERGE_MSG"));
815 fprintf(fp
, "\nConflicts:\n");
816 for (pos
= 0; pos
< active_nr
; pos
++) {
817 struct cache_entry
*ce
= active_cache
[pos
];
820 fprintf(fp
, "\t%s\n", ce
->name
);
821 while (pos
+ 1 < active_nr
&&
823 active_cache
[pos
+ 1]->name
))
829 printf("Automatic merge failed; "
830 "fix conflicts and then commit the result.\n");
834 static struct commit
*is_old_style_invocation(int argc
, const char **argv
)
836 struct commit
*second_token
= NULL
;
838 unsigned char second_sha1
[20];
840 if (get_sha1(argv
[1], second_sha1
))
842 second_token
= lookup_commit_reference_gently(second_sha1
, 0);
844 die("'%s' is not a commit", argv
[1]);
845 if (hashcmp(second_token
->object
.sha1
, head
))
851 static int evaluate_result(void)
856 /* Check how many files differ. */
857 init_revisions(&rev
, "");
858 setup_revisions(0, NULL
, &rev
, NULL
);
859 rev
.diffopt
.output_format
|=
860 DIFF_FORMAT_CALLBACK
;
861 rev
.diffopt
.format_callback
= count_diff_files
;
862 rev
.diffopt
.format_callback_data
= &cnt
;
863 run_diff_files(&rev
, 0);
866 * Check how many unmerged entries are
869 cnt
+= count_unmerged_entries();
874 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
876 unsigned char result_tree
[20];
877 struct strbuf buf
= STRBUF_INIT
;
878 const char *head_arg
;
879 int flag
, head_invalid
= 0, i
;
880 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
881 struct commit_list
*common
= NULL
;
882 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
883 struct commit_list
**remotes
= &remoteheads
;
885 if (file_exists(git_path("MERGE_HEAD")))
886 die("You have not concluded your merge. (MERGE_HEAD exists)");
887 if (read_cache_unmerged())
888 die("You are in the middle of a conflicted merge."
889 " (index unmerged)");
892 * Check if we are _not_ on a detached HEAD, i.e. if there is a
895 branch
= resolve_ref("HEAD", head
, 0, &flag
);
896 if (branch
&& !prefixcmp(branch
, "refs/heads/"))
898 if (is_null_sha1(head
))
901 git_config(git_merge_config
, NULL
);
904 if (diff_use_color_default
== -1)
905 diff_use_color_default
= git_use_color_default
;
907 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
908 builtin_merge_usage
, 0);
913 if (!allow_fast_forward
)
914 die("You cannot combine --squash with --no-ff.");
918 if (!allow_fast_forward
&& fast_forward_only
)
919 die("You cannot combine --no-ff with --ff-only.");
922 usage_with_options(builtin_merge_usage
,
923 builtin_merge_options
);
926 * This could be traditional "merge <msg> HEAD <commit>..." and
927 * the way we can tell it is to see if the second token is HEAD,
928 * but some people might have misused the interface and used a
929 * committish that is the same as HEAD there instead.
930 * Traditional format never would have "-m" so it is an
931 * additional safety measure to check for it.
934 if (!have_message
&& is_old_style_invocation(argc
, argv
)) {
935 strbuf_addstr(&merge_msg
, argv
[0]);
939 } else if (head_invalid
) {
940 struct object
*remote_head
;
942 * If the merged head is a valid one there is no reason
943 * to forbid "git merge" into a branch yet to be born.
944 * We do the same for "git pull".
947 die("Can merge only exactly one commit into "
950 die("Squash commit into empty head not supported yet");
951 if (!allow_fast_forward
)
952 die("Non-fast-forward commit does not make sense into "
954 remote_head
= peel_to_type(argv
[0], 0, NULL
, OBJ_COMMIT
);
956 die("%s - not something we can merge", argv
[0]);
957 update_ref("initial pull", "HEAD", remote_head
->sha1
, NULL
, 0,
959 reset_hard(remote_head
->sha1
, 0);
962 struct strbuf msg
= STRBUF_INIT
;
964 /* We are invoked directly as the first-class UI. */
968 * All the rest are the commits being merged;
969 * prepare the standard merge summary message to
970 * be appended to the given message. If remote
971 * is invalid we will die later in the common
972 * codepath so we discard the error in this
975 for (i
= 0; i
< argc
; i
++)
976 merge_name(argv
[i
], &msg
);
977 fmt_merge_msg(option_log
, &msg
, &merge_msg
);
979 strbuf_setlen(&merge_msg
, merge_msg
.len
-1);
982 if (head_invalid
|| !argc
)
983 usage_with_options(builtin_merge_usage
,
984 builtin_merge_options
);
986 strbuf_addstr(&buf
, "merge");
987 for (i
= 0; i
< argc
; i
++)
988 strbuf_addf(&buf
, " %s", argv
[i
]);
989 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
992 for (i
= 0; i
< argc
; i
++) {
994 struct commit
*commit
;
996 o
= peel_to_type(argv
[i
], 0, NULL
, OBJ_COMMIT
);
998 die("%s - not something we can merge", argv
[i
]);
999 commit
= lookup_commit(o
->sha1
);
1000 commit
->util
= (void *)argv
[i
];
1001 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1003 strbuf_addf(&buf
, "GITHEAD_%s", sha1_to_hex(o
->sha1
));
1004 setenv(buf
.buf
, argv
[i
], 1);
1008 if (!use_strategies
) {
1009 if (!remoteheads
->next
)
1010 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
1012 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
1015 for (i
= 0; i
< use_strategies_nr
; i
++) {
1016 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
1017 allow_fast_forward
= 0;
1018 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
1022 if (!remoteheads
->next
)
1023 common
= get_merge_bases(lookup_commit(head
),
1024 remoteheads
->item
, 1);
1026 struct commit_list
*list
= remoteheads
;
1027 commit_list_insert(lookup_commit(head
), &list
);
1028 common
= get_octopus_merge_bases(list
);
1032 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head
, NULL
, 0,
1036 ; /* No common ancestors found. We need a real merge. */
1037 else if (!remoteheads
->next
&& !common
->next
&&
1038 common
->item
== remoteheads
->item
) {
1040 * If head can reach all the merge then we are up to date.
1041 * but first the most common case of merging one remote.
1043 finish_up_to_date("Already up-to-date.");
1045 } else if (allow_fast_forward
&& !remoteheads
->next
&&
1047 !hashcmp(common
->item
->object
.sha1
, head
)) {
1048 /* Again the most common case of merging one remote. */
1049 struct strbuf msg
= STRBUF_INIT
;
1053 strcpy(hex
, find_unique_abbrev(head
, DEFAULT_ABBREV
));
1056 printf("Updating %s..%s\n",
1058 find_unique_abbrev(remoteheads
->item
->object
.sha1
,
1060 strbuf_addstr(&msg
, "Fast-forward");
1063 " (no commit created; -m option ignored)");
1064 o
= peel_to_type(sha1_to_hex(remoteheads
->item
->object
.sha1
),
1065 0, NULL
, OBJ_COMMIT
);
1069 if (checkout_fast_forward(head
, remoteheads
->item
->object
.sha1
))
1072 finish(o
->sha1
, msg
.buf
);
1075 } else if (!remoteheads
->next
&& common
->next
)
1078 * We are not doing octopus and not fast-forward. Need
1081 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1083 * We are not doing octopus, not fast-forward, and have
1086 refresh_cache(REFRESH_QUIET
);
1087 if (allow_trivial
&& !fast_forward_only
) {
1088 /* See if it is really trivial. */
1089 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1090 printf("Trying really trivial in-index merge...\n");
1091 if (!read_tree_trivial(common
->item
->object
.sha1
,
1092 head
, remoteheads
->item
->object
.sha1
))
1093 return merge_trivial();
1098 * An octopus. If we can reach all the remote we are up
1102 struct commit_list
*j
;
1104 for (j
= remoteheads
; j
; j
= j
->next
) {
1105 struct commit_list
*common_one
;
1108 * Here we *have* to calculate the individual
1109 * merge_bases again, otherwise "git merge HEAD^
1110 * HEAD^^" would be missed.
1112 common_one
= get_merge_bases(lookup_commit(head
),
1114 if (hashcmp(common_one
->item
->object
.sha1
,
1115 j
->item
->object
.sha1
)) {
1121 finish_up_to_date("Already up-to-date. Yeeah!");
1126 if (fast_forward_only
)
1127 die("Not possible to fast-forward, aborting.");
1129 /* We are going to make a new commit. */
1130 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1133 * At this point, we need a real merge. No matter what strategy
1134 * we use, it would operate on the index, possibly affecting the
1135 * working tree, and when resolved cleanly, have the desired
1136 * tree in the index -- this means that the index must be in
1137 * sync with the head commit. The strategies are responsible
1140 if (use_strategies_nr
!= 1) {
1142 * Stash away the local changes so that we can try more
1147 memcpy(stash
, null_sha1
, 20);
1150 for (i
= 0; i
< use_strategies_nr
; i
++) {
1153 printf("Rewinding the tree to pristine...\n");
1156 if (use_strategies_nr
!= 1)
1157 printf("Trying merge strategy %s...\n",
1158 use_strategies
[i
]->name
);
1160 * Remember which strategy left the state in the working
1163 wt_strategy
= use_strategies
[i
]->name
;
1165 ret
= try_merge_strategy(use_strategies
[i
]->name
,
1167 if (!option_commit
&& !ret
) {
1170 * This is necessary here just to avoid writing
1171 * the tree, but later we will *not* exit with
1172 * status code 1 because merge_was_ok is set.
1179 * The backend exits with 1 when conflicts are
1180 * left to be resolved, with 2 when it does not
1181 * handle the given merge at all.
1184 int cnt
= evaluate_result();
1186 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1187 best_strategy
= use_strategies
[i
]->name
;
1197 /* Automerge succeeded. */
1198 write_tree_trivial(result_tree
);
1199 automerge_was_ok
= 1;
1204 * If we have a resulting tree, that means the strategy module
1205 * auto resolved the merge cleanly.
1207 if (automerge_was_ok
)
1208 return finish_automerge(common
, result_tree
, wt_strategy
);
1211 * Pick the result from the best strategy and have the user fix
1214 if (!best_strategy
) {
1216 if (use_strategies_nr
> 1)
1218 "No merge strategy handled the merge.\n");
1220 fprintf(stderr
, "Merge with strategy %s failed.\n",
1221 use_strategies
[0]->name
);
1223 } else if (best_strategy
== wt_strategy
)
1224 ; /* We already have its result in the working tree. */
1226 printf("Rewinding the tree to pristine...\n");
1228 printf("Using the %s to prepare resolving by hand.\n",
1230 try_merge_strategy(best_strategy
, common
, head_arg
);
1237 struct commit_list
*j
;
1239 for (j
= remoteheads
; j
; j
= j
->next
)
1240 strbuf_addf(&buf
, "%s\n",
1241 sha1_to_hex(j
->item
->object
.sha1
));
1242 fd
= open(git_path("MERGE_HEAD"), O_WRONLY
| O_CREAT
, 0666);
1244 die_errno("Could not open '%s' for writing",
1245 git_path("MERGE_HEAD"));
1246 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1247 die_errno("Could not write to '%s'", git_path("MERGE_HEAD"));
1249 strbuf_addch(&merge_msg
, '\n');
1250 fd
= open(git_path("MERGE_MSG"), O_WRONLY
| O_CREAT
, 0666);
1252 die_errno("Could not open '%s' for writing",
1253 git_path("MERGE_MSG"));
1254 if (write_in_full(fd
, merge_msg
.buf
, merge_msg
.len
) !=
1256 die_errno("Could not write to '%s'", git_path("MERGE_MSG"));
1258 fd
= open(git_path("MERGE_MODE"), O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
1260 die_errno("Could not open '%s' for writing",
1261 git_path("MERGE_MODE"));
1263 if (!allow_fast_forward
)
1264 strbuf_addf(&buf
, "no-ff");
1265 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1266 die_errno("Could not write to '%s'", git_path("MERGE_MODE"));
1271 fprintf(stderr
, "Automatic merge went well; "
1272 "stopped before committing as requested\n");
1275 return suggest_conflicts();