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"
27 #include "resolve-undo.h"
29 #include "gpg-interface.h"
31 #define DEFAULT_TWOHEAD (1<<0)
32 #define DEFAULT_OCTOPUS (1<<1)
33 #define NO_FAST_FORWARD (1<<2)
34 #define NO_TRIVIAL (1<<3)
41 static const char * const builtin_merge_usage
[] = {
42 "git merge [options] [<commit>...]",
43 "git merge [options] <msg> HEAD <commit>",
48 static int show_diffstat
= 1, shortlog_len
, squash
;
49 static int option_commit
= 1, allow_fast_forward
= 1;
50 static int fast_forward_only
, option_edit
;
51 static int allow_trivial
= 1, have_message
;
52 static struct strbuf merge_msg
;
53 static struct commit_list
*remoteheads
;
54 static struct strategy
**use_strategies
;
55 static size_t use_strategies_nr
, use_strategies_alloc
;
56 static const char **xopts
;
57 static size_t xopts_nr
, xopts_alloc
;
58 static const char *branch
;
59 static char *branch_mergeoptions
;
60 static int option_renormalize
;
62 static int allow_rerere_auto
;
63 static int abort_current_merge
;
64 static int show_progress
= -1;
65 static int default_to_upstream
;
66 static const char *sign_commit
;
68 static struct strategy all_strategy
[] = {
69 { "recursive", DEFAULT_TWOHEAD
| NO_TRIVIAL
},
70 { "octopus", DEFAULT_OCTOPUS
},
72 { "ours", NO_FAST_FORWARD
| NO_TRIVIAL
},
73 { "subtree", NO_FAST_FORWARD
| NO_TRIVIAL
},
76 static const char *pull_twohead
, *pull_octopus
;
78 static int option_parse_message(const struct option
*opt
,
79 const char *arg
, int unset
)
81 struct strbuf
*buf
= opt
->value
;
84 strbuf_setlen(buf
, 0);
86 strbuf_addf(buf
, "%s%s", buf
->len
? "\n\n" : "", arg
);
89 return error(_("switch `m' requires a value"));
93 static struct strategy
*get_strategy(const char *name
)
97 static struct cmdnames main_cmds
, other_cmds
;
103 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
104 if (!strcmp(name
, all_strategy
[i
].name
))
105 return &all_strategy
[i
];
108 struct cmdnames not_strategies
;
111 memset(¬_strategies
, 0, sizeof(struct cmdnames
));
112 load_command_list("git-merge-", &main_cmds
, &other_cmds
);
113 for (i
= 0; i
< main_cmds
.cnt
; i
++) {
115 struct cmdname
*ent
= main_cmds
.names
[i
];
116 for (j
= 0; j
< ARRAY_SIZE(all_strategy
); j
++)
117 if (!strncmp(ent
->name
, all_strategy
[j
].name
, ent
->len
)
118 && !all_strategy
[j
].name
[ent
->len
])
121 add_cmdname(¬_strategies
, ent
->name
, ent
->len
);
123 exclude_cmds(&main_cmds
, ¬_strategies
);
125 if (!is_in_cmdlist(&main_cmds
, name
) && !is_in_cmdlist(&other_cmds
, name
)) {
126 fprintf(stderr
, _("Could not find merge strategy '%s'.\n"), name
);
127 fprintf(stderr
, _("Available strategies are:"));
128 for (i
= 0; i
< main_cmds
.cnt
; i
++)
129 fprintf(stderr
, " %s", main_cmds
.names
[i
]->name
);
130 fprintf(stderr
, ".\n");
131 if (other_cmds
.cnt
) {
132 fprintf(stderr
, _("Available custom strategies are:"));
133 for (i
= 0; i
< other_cmds
.cnt
; i
++)
134 fprintf(stderr
, " %s", other_cmds
.names
[i
]->name
);
135 fprintf(stderr
, ".\n");
140 ret
= xcalloc(1, sizeof(struct strategy
));
141 ret
->name
= xstrdup(name
);
142 ret
->attr
= NO_TRIVIAL
;
146 static void append_strategy(struct strategy
*s
)
148 ALLOC_GROW(use_strategies
, use_strategies_nr
+ 1, use_strategies_alloc
);
149 use_strategies
[use_strategies_nr
++] = s
;
152 static int option_parse_strategy(const struct option
*opt
,
153 const char *name
, int unset
)
158 append_strategy(get_strategy(name
));
162 static int option_parse_x(const struct option
*opt
,
163 const char *arg
, int unset
)
168 ALLOC_GROW(xopts
, xopts_nr
+ 1, xopts_alloc
);
169 xopts
[xopts_nr
++] = xstrdup(arg
);
173 static int option_parse_n(const struct option
*opt
,
174 const char *arg
, int unset
)
176 show_diffstat
= unset
;
180 static struct option builtin_merge_options
[] = {
181 { OPTION_CALLBACK
, 'n', NULL
, NULL
, NULL
,
182 "do not show a diffstat at the end of the merge",
183 PARSE_OPT_NOARG
, option_parse_n
},
184 OPT_BOOLEAN(0, "stat", &show_diffstat
,
185 "show a diffstat at the end of the merge"),
186 OPT_BOOLEAN(0, "summary", &show_diffstat
, "(synonym to --stat)"),
187 { OPTION_INTEGER
, 0, "log", &shortlog_len
, "n",
188 "add (at most <n>) entries from shortlog to merge commit message",
189 PARSE_OPT_OPTARG
, NULL
, DEFAULT_MERGE_LOG_LEN
},
190 OPT_BOOLEAN(0, "squash", &squash
,
191 "create a single commit instead of doing a merge"),
192 OPT_BOOLEAN(0, "commit", &option_commit
,
193 "perform a commit if the merge succeeds (default)"),
194 OPT_BOOLEAN('e', "edit", &option_edit
,
195 "edit message before committing"),
196 OPT_BOOLEAN(0, "ff", &allow_fast_forward
,
197 "allow fast-forward (default)"),
198 OPT_BOOLEAN(0, "ff-only", &fast_forward_only
,
199 "abort if fast-forward is not possible"),
200 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto
),
201 OPT_CALLBACK('s', "strategy", &use_strategies
, "strategy",
202 "merge strategy to use", option_parse_strategy
),
203 OPT_CALLBACK('X', "strategy-option", &xopts
, "option=value",
204 "option for selected merge strategy", option_parse_x
),
205 OPT_CALLBACK('m', "message", &merge_msg
, "message",
206 "merge commit message (for a non-fast-forward merge)",
207 option_parse_message
),
208 OPT__VERBOSITY(&verbosity
),
209 OPT_BOOLEAN(0, "abort", &abort_current_merge
,
210 "abort the current in-progress merge"),
211 OPT_SET_INT(0, "progress", &show_progress
, "force progress reporting", 1),
212 { OPTION_STRING
, 'S', "gpg-sign", &sign_commit
, "key id",
213 "GPG sign commit", PARSE_OPT_OPTARG
, NULL
, (intptr_t) "" },
217 /* Cleans up metadata that is uninteresting after a succeeded merge. */
218 static void drop_save(void)
220 unlink(git_path("MERGE_HEAD"));
221 unlink(git_path("MERGE_MSG"));
222 unlink(git_path("MERGE_MODE"));
225 static int save_state(unsigned char *stash
)
228 struct child_process cp
;
229 struct strbuf buffer
= STRBUF_INIT
;
230 const char *argv
[] = {"stash", "create", NULL
};
232 memset(&cp
, 0, sizeof(cp
));
237 if (start_command(&cp
))
238 die(_("could not run stash."));
239 len
= strbuf_read(&buffer
, cp
.out
, 1024);
242 if (finish_command(&cp
) || len
< 0)
243 die(_("stash failed"));
244 else if (!len
) /* no changes */
246 strbuf_setlen(&buffer
, buffer
.len
-1);
247 if (get_sha1(buffer
.buf
, stash
))
248 die(_("not a valid object: %s"), buffer
.buf
);
252 static void read_empty(unsigned const char *sha1
, int verbose
)
257 args
[i
++] = "read-tree";
262 args
[i
++] = EMPTY_TREE_SHA1_HEX
;
263 args
[i
++] = sha1_to_hex(sha1
);
266 if (run_command_v_opt(args
, RUN_GIT_CMD
))
267 die(_("read-tree failed"));
270 static void reset_hard(unsigned const char *sha1
, int verbose
)
275 args
[i
++] = "read-tree";
278 args
[i
++] = "--reset";
280 args
[i
++] = sha1_to_hex(sha1
);
283 if (run_command_v_opt(args
, RUN_GIT_CMD
))
284 die(_("read-tree failed"));
287 static void restore_state(const unsigned char *head
,
288 const unsigned char *stash
)
290 struct strbuf sb
= STRBUF_INIT
;
291 const char *args
[] = { "stash", "apply", NULL
, NULL
};
293 if (is_null_sha1(stash
))
298 args
[2] = sha1_to_hex(stash
);
301 * It is OK to ignore error here, for example when there was
302 * nothing to restore.
304 run_command_v_opt(args
, RUN_GIT_CMD
);
307 refresh_cache(REFRESH_QUIET
);
310 /* This is called when no merge was necessary. */
311 static void finish_up_to_date(const char *msg
)
314 printf("%s%s\n", squash
? _(" (nothing to squash)") : "", msg
);
318 static void squash_message(struct commit
*commit
)
321 struct strbuf out
= STRBUF_INIT
;
322 struct commit_list
*j
;
324 struct pretty_print_context ctx
= {0};
326 printf(_("Squash commit -- not updating HEAD\n"));
327 fd
= open(git_path("SQUASH_MSG"), O_WRONLY
| O_CREAT
, 0666);
329 die_errno(_("Could not write to '%s'"), git_path("SQUASH_MSG"));
331 init_revisions(&rev
, NULL
);
332 rev
.ignore_merges
= 1;
333 rev
.commit_format
= CMIT_FMT_MEDIUM
;
335 commit
->object
.flags
|= UNINTERESTING
;
336 add_pending_object(&rev
, &commit
->object
, NULL
);
338 for (j
= remoteheads
; j
; j
= j
->next
)
339 add_pending_object(&rev
, &j
->item
->object
, NULL
);
341 setup_revisions(0, NULL
, &rev
, NULL
);
342 if (prepare_revision_walk(&rev
))
343 die(_("revision walk setup failed"));
345 ctx
.abbrev
= rev
.abbrev
;
346 ctx
.date_mode
= rev
.date_mode
;
347 ctx
.fmt
= rev
.commit_format
;
349 strbuf_addstr(&out
, "Squashed commit of the following:\n");
350 while ((commit
= get_revision(&rev
)) != NULL
) {
351 strbuf_addch(&out
, '\n');
352 strbuf_addf(&out
, "commit %s\n",
353 sha1_to_hex(commit
->object
.sha1
));
354 pretty_print_commit(&ctx
, commit
, &out
);
356 if (write(fd
, out
.buf
, out
.len
) < 0)
357 die_errno(_("Writing SQUASH_MSG"));
359 die_errno(_("Finishing SQUASH_MSG"));
360 strbuf_release(&out
);
363 static void finish(struct commit
*head_commit
,
364 const unsigned char *new_head
, const char *msg
)
366 struct strbuf reflog_message
= STRBUF_INIT
;
367 const unsigned char *head
= head_commit
->object
.sha1
;
370 strbuf_addstr(&reflog_message
, getenv("GIT_REFLOG_ACTION"));
374 strbuf_addf(&reflog_message
, "%s: %s",
375 getenv("GIT_REFLOG_ACTION"), msg
);
378 squash_message(head_commit
);
380 if (verbosity
>= 0 && !merge_msg
.len
)
381 printf(_("No merge message -- not updating HEAD\n"));
383 const char *argv_gc_auto
[] = { "gc", "--auto", NULL
};
384 update_ref(reflog_message
.buf
, "HEAD",
388 * We ignore errors in 'gc --auto', since the
389 * user should see them.
391 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
394 if (new_head
&& show_diffstat
) {
395 struct diff_options opts
;
397 opts
.output_format
|=
398 DIFF_FORMAT_SUMMARY
| DIFF_FORMAT_DIFFSTAT
;
399 opts
.detect_rename
= DIFF_DETECT_RENAME
;
400 if (diff_setup_done(&opts
) < 0)
401 die(_("diff_setup_done failed"));
402 diff_tree_sha1(head
, new_head
, "", &opts
);
407 /* Run a post-merge hook */
408 run_hook(NULL
, "post-merge", squash
? "1" : "0", NULL
);
410 strbuf_release(&reflog_message
);
413 /* Get the name for the merge commit's message. */
414 static void merge_name(const char *remote
, struct strbuf
*msg
)
416 struct commit
*remote_head
;
417 unsigned char branch_head
[20], buf_sha
[20];
418 struct strbuf buf
= STRBUF_INIT
;
419 struct strbuf bname
= STRBUF_INIT
;
424 strbuf_branchname(&bname
, remote
);
427 memset(branch_head
, 0, sizeof(branch_head
));
428 remote_head
= get_merge_parent(remote
);
430 die(_("'%s' does not point to a commit"), remote
);
432 if (dwim_ref(remote
, strlen(remote
), branch_head
, &found_ref
) > 0) {
433 if (!prefixcmp(found_ref
, "refs/heads/")) {
434 strbuf_addf(msg
, "%s\t\tbranch '%s' of .\n",
435 sha1_to_hex(branch_head
), remote
);
438 if (!prefixcmp(found_ref
, "refs/tags/")) {
439 strbuf_addf(msg
, "%s\t\ttag '%s' of .\n",
440 sha1_to_hex(branch_head
), remote
);
443 if (!prefixcmp(found_ref
, "refs/remotes/")) {
444 strbuf_addf(msg
, "%s\t\tremote-tracking branch '%s' of .\n",
445 sha1_to_hex(branch_head
), remote
);
450 /* See if remote matches <name>^^^.. or <name>~<number> */
451 for (len
= 0, ptr
= remote
+ strlen(remote
);
452 remote
< ptr
&& ptr
[-1] == '^';
459 ptr
= strrchr(remote
, '~');
461 int seen_nonzero
= 0;
464 while (*++ptr
&& isdigit(*ptr
)) {
465 seen_nonzero
|= (*ptr
!= '0');
469 len
= 0; /* not ...~<number> */
470 else if (seen_nonzero
)
473 early
= 1; /* "name~" is "name~1"! */
477 struct strbuf truname
= STRBUF_INIT
;
478 strbuf_addstr(&truname
, "refs/heads/");
479 strbuf_addstr(&truname
, remote
);
480 strbuf_setlen(&truname
, truname
.len
- len
);
481 if (resolve_ref(truname
.buf
, buf_sha
, 1, NULL
)) {
483 "%s\t\tbranch '%s'%s of .\n",
484 sha1_to_hex(remote_head
->object
.sha1
),
486 (early
? " (early part)" : ""));
487 strbuf_release(&truname
);
492 if (!strcmp(remote
, "FETCH_HEAD") &&
493 !access(git_path("FETCH_HEAD"), R_OK
)) {
495 struct strbuf line
= STRBUF_INIT
;
498 fp
= fopen(git_path("FETCH_HEAD"), "r");
500 die_errno(_("could not open '%s' for reading"),
501 git_path("FETCH_HEAD"));
502 strbuf_getline(&line
, fp
, '\n');
504 ptr
= strstr(line
.buf
, "\tnot-for-merge\t");
506 strbuf_remove(&line
, ptr
-line
.buf
+1, 13);
507 strbuf_addbuf(msg
, &line
);
508 strbuf_release(&line
);
511 strbuf_addf(msg
, "%s\t\tcommit '%s'\n",
512 sha1_to_hex(remote_head
->object
.sha1
), remote
);
514 strbuf_release(&buf
);
515 strbuf_release(&bname
);
518 static void parse_branch_merge_options(char *bmo
)
525 argc
= split_cmdline(bmo
, &argv
);
527 die(_("Bad branch.%s.mergeoptions string: %s"), branch
,
528 split_cmdline_strerror(argc
));
529 argv
= xrealloc(argv
, sizeof(*argv
) * (argc
+ 2));
530 memmove(argv
+ 1, argv
, sizeof(*argv
) * (argc
+ 1));
532 argv
[0] = "branch.*.mergeoptions";
533 parse_options(argc
, argv
, NULL
, builtin_merge_options
,
534 builtin_merge_usage
, 0);
538 static int git_merge_config(const char *k
, const char *v
, void *cb
)
542 if (branch
&& !prefixcmp(k
, "branch.") &&
543 !prefixcmp(k
+ 7, branch
) &&
544 !strcmp(k
+ 7 + strlen(branch
), ".mergeoptions")) {
545 free(branch_mergeoptions
);
546 branch_mergeoptions
= xstrdup(v
);
550 if (!strcmp(k
, "merge.diffstat") || !strcmp(k
, "merge.stat"))
551 show_diffstat
= git_config_bool(k
, v
);
552 else if (!strcmp(k
, "pull.twohead"))
553 return git_config_string(&pull_twohead
, k
, v
);
554 else if (!strcmp(k
, "pull.octopus"))
555 return git_config_string(&pull_octopus
, k
, v
);
556 else if (!strcmp(k
, "merge.renormalize"))
557 option_renormalize
= git_config_bool(k
, v
);
558 else if (!strcmp(k
, "merge.log") || !strcmp(k
, "merge.summary")) {
560 shortlog_len
= git_config_bool_or_int(k
, v
, &is_bool
);
561 if (!is_bool
&& shortlog_len
< 0)
562 return error(_("%s: negative length %s"), k
, v
);
563 if (is_bool
&& shortlog_len
)
564 shortlog_len
= DEFAULT_MERGE_LOG_LEN
;
566 } else if (!strcmp(k
, "merge.ff")) {
567 int boolval
= git_config_maybe_bool(k
, v
);
569 allow_fast_forward
= boolval
;
570 } else if (v
&& !strcmp(v
, "only")) {
571 allow_fast_forward
= 1;
572 fast_forward_only
= 1;
573 } /* do not barf on values from future versions of git */
575 } else if (!strcmp(k
, "merge.defaulttoupstream")) {
576 default_to_upstream
= git_config_bool(k
, v
);
580 status
= git_gpg_config(k
, v
, NULL
);
583 return git_diff_ui_config(k
, v
, cb
);
586 static int read_tree_trivial(unsigned char *common
, unsigned char *head
,
590 struct tree
*trees
[MAX_UNPACK_TREES
];
591 struct tree_desc t
[MAX_UNPACK_TREES
];
592 struct unpack_trees_options opts
;
594 memset(&opts
, 0, sizeof(opts
));
596 opts
.src_index
= &the_index
;
597 opts
.dst_index
= &the_index
;
599 opts
.verbose_update
= 1;
600 opts
.trivial_merges_only
= 1;
602 trees
[nr_trees
] = parse_tree_indirect(common
);
603 if (!trees
[nr_trees
++])
605 trees
[nr_trees
] = parse_tree_indirect(head
);
606 if (!trees
[nr_trees
++])
608 trees
[nr_trees
] = parse_tree_indirect(one
);
609 if (!trees
[nr_trees
++])
611 opts
.fn
= threeway_merge
;
612 cache_tree_free(&active_cache_tree
);
613 for (i
= 0; i
< nr_trees
; i
++) {
614 parse_tree(trees
[i
]);
615 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
617 if (unpack_trees(nr_trees
, t
, &opts
))
622 static void write_tree_trivial(unsigned char *sha1
)
624 if (write_cache_as_tree(sha1
, 0, NULL
))
625 die(_("git write-tree failed to write a tree"));
628 static const char *merge_argument(struct commit
*commit
)
631 return sha1_to_hex(commit
->object
.sha1
);
633 return EMPTY_TREE_SHA1_HEX
;
636 int try_merge_command(const char *strategy
, size_t xopts_nr
,
637 const char **xopts
, struct commit_list
*common
,
638 const char *head_arg
, struct commit_list
*remotes
)
641 int i
= 0, x
= 0, ret
;
642 struct commit_list
*j
;
643 struct strbuf buf
= STRBUF_INIT
;
645 args
= xmalloc((4 + xopts_nr
+ commit_list_count(common
) +
646 commit_list_count(remotes
)) * sizeof(char *));
647 strbuf_addf(&buf
, "merge-%s", strategy
);
649 for (x
= 0; x
< xopts_nr
; x
++) {
650 char *s
= xmalloc(strlen(xopts
[x
])+2+1);
652 strcpy(s
+2, xopts
[x
]);
655 for (j
= common
; j
; j
= j
->next
)
656 args
[i
++] = xstrdup(merge_argument(j
->item
));
658 args
[i
++] = head_arg
;
659 for (j
= remotes
; j
; j
= j
->next
)
660 args
[i
++] = xstrdup(merge_argument(j
->item
));
662 ret
= run_command_v_opt(args
, RUN_GIT_CMD
);
663 strbuf_release(&buf
);
665 for (x
= 0; x
< xopts_nr
; x
++)
666 free((void *)args
[i
++]);
667 for (j
= common
; j
; j
= j
->next
)
668 free((void *)args
[i
++]);
670 for (j
= remotes
; j
; j
= j
->next
)
671 free((void *)args
[i
++]);
674 if (read_cache() < 0)
675 die(_("failed to read the cache"));
676 resolve_undo_clear();
681 static int try_merge_strategy(const char *strategy
, struct commit_list
*common
,
682 struct commit
*head
, const char *head_arg
)
685 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
687 index_fd
= hold_locked_index(lock
, 1);
688 refresh_cache(REFRESH_QUIET
);
689 if (active_cache_changed
&&
690 (write_cache(index_fd
, active_cache
, active_nr
) ||
691 commit_locked_index(lock
)))
692 return error(_("Unable to write index."));
693 rollback_lock_file(lock
);
695 if (!strcmp(strategy
, "recursive") || !strcmp(strategy
, "subtree")) {
697 struct commit
*result
;
698 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
700 struct commit_list
*reversed
= NULL
;
701 struct merge_options o
;
702 struct commit_list
*j
;
704 if (remoteheads
->next
) {
705 error(_("Not handling anything other than two heads merge."));
709 init_merge_options(&o
);
710 if (!strcmp(strategy
, "subtree"))
711 o
.subtree_shift
= "";
713 o
.renormalize
= option_renormalize
;
714 o
.show_rename_progress
=
715 show_progress
== -1 ? isatty(2) : show_progress
;
717 for (x
= 0; x
< xopts_nr
; x
++)
718 if (parse_merge_opt(&o
, xopts
[x
]))
719 die(_("Unknown option for merge-recursive: -X%s"), xopts
[x
]);
721 o
.branch1
= head_arg
;
722 o
.branch2
= merge_remote_util(remoteheads
->item
)->name
;
724 for (j
= common
; j
; j
= j
->next
)
725 commit_list_insert(j
->item
, &reversed
);
727 index_fd
= hold_locked_index(lock
, 1);
728 clean
= merge_recursive(&o
, head
,
729 remoteheads
->item
, reversed
, &result
);
730 if (active_cache_changed
&&
731 (write_cache(index_fd
, active_cache
, active_nr
) ||
732 commit_locked_index(lock
)))
733 die (_("unable to write %s"), get_index_file());
734 rollback_lock_file(lock
);
735 return clean
? 0 : 1;
737 return try_merge_command(strategy
, xopts_nr
, xopts
,
738 common
, head_arg
, remoteheads
);
742 static void count_diff_files(struct diff_queue_struct
*q
,
743 struct diff_options
*opt
, void *data
)
750 static int count_unmerged_entries(void)
754 for (i
= 0; i
< active_nr
; i
++)
755 if (ce_stage(active_cache
[i
]))
761 int checkout_fast_forward(const unsigned char *head
, const unsigned char *remote
)
763 struct tree
*trees
[MAX_UNPACK_TREES
];
764 struct unpack_trees_options opts
;
765 struct tree_desc t
[MAX_UNPACK_TREES
];
766 int i
, fd
, nr_trees
= 0;
767 struct dir_struct dir
;
768 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
770 refresh_cache(REFRESH_QUIET
);
772 fd
= hold_locked_index(lock_file
, 1);
774 memset(&trees
, 0, sizeof(trees
));
775 memset(&opts
, 0, sizeof(opts
));
776 memset(&t
, 0, sizeof(t
));
777 memset(&dir
, 0, sizeof(dir
));
778 dir
.flags
|= DIR_SHOW_IGNORED
;
779 dir
.exclude_per_dir
= ".gitignore";
783 opts
.src_index
= &the_index
;
784 opts
.dst_index
= &the_index
;
786 opts
.verbose_update
= 1;
788 opts
.fn
= twoway_merge
;
789 setup_unpack_trees_porcelain(&opts
, "merge");
791 trees
[nr_trees
] = parse_tree_indirect(head
);
792 if (!trees
[nr_trees
++])
794 trees
[nr_trees
] = parse_tree_indirect(remote
);
795 if (!trees
[nr_trees
++])
797 for (i
= 0; i
< nr_trees
; i
++) {
798 parse_tree(trees
[i
]);
799 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
801 if (unpack_trees(nr_trees
, t
, &opts
))
803 if (write_cache(fd
, active_cache
, active_nr
) ||
804 commit_locked_index(lock_file
))
805 die(_("unable to write new index file"));
809 static void split_merge_strategies(const char *string
, struct strategy
**list
,
817 buf
= xstrdup(string
);
822 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
823 (*list
)[(*nr
)++].name
= xstrdup(q
);
828 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
829 (*list
)[(*nr
)++].name
= xstrdup(q
);
835 static void add_strategies(const char *string
, unsigned attr
)
837 struct strategy
*list
= NULL
;
838 int list_alloc
= 0, list_nr
= 0, i
;
840 memset(&list
, 0, sizeof(list
));
841 split_merge_strategies(string
, &list
, &list_nr
, &list_alloc
);
843 for (i
= 0; i
< list_nr
; i
++)
844 append_strategy(get_strategy(list
[i
].name
));
847 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
848 if (all_strategy
[i
].attr
& attr
)
849 append_strategy(&all_strategy
[i
]);
853 static void write_merge_msg(struct strbuf
*msg
)
855 int fd
= open(git_path("MERGE_MSG"), O_WRONLY
| O_CREAT
, 0666);
857 die_errno(_("Could not open '%s' for writing"),
858 git_path("MERGE_MSG"));
859 if (write_in_full(fd
, msg
->buf
, msg
->len
) != msg
->len
)
860 die_errno(_("Could not write to '%s'"), git_path("MERGE_MSG"));
864 static void read_merge_msg(struct strbuf
*msg
)
867 if (strbuf_read_file(msg
, git_path("MERGE_MSG"), 0) < 0)
868 die_errno(_("Could not read from '%s'"), git_path("MERGE_MSG"));
871 static void write_merge_state(void);
872 static void abort_commit(const char *err_msg
)
875 error("%s", err_msg
);
877 _("Not committing merge; use 'git commit' to complete the merge.\n"));
882 static void prepare_to_commit(void)
884 struct strbuf msg
= STRBUF_INIT
;
885 strbuf_addbuf(&msg
, &merge_msg
);
886 strbuf_addch(&msg
, '\n');
887 write_merge_msg(&msg
);
888 run_hook(get_index_file(), "prepare-commit-msg",
889 git_path("MERGE_MSG"), "merge", NULL
, NULL
);
891 if (launch_editor(git_path("MERGE_MSG"), NULL
, NULL
))
894 read_merge_msg(&msg
);
895 stripspace(&msg
, option_edit
);
897 abort_commit(_("Empty commit message."));
898 strbuf_release(&merge_msg
);
899 strbuf_addbuf(&merge_msg
, &msg
);
900 strbuf_release(&msg
);
903 static int merge_trivial(struct commit
*head
)
905 unsigned char result_tree
[20], result_commit
[20];
906 struct commit_list
*parent
= xmalloc(sizeof(*parent
));
908 write_tree_trivial(result_tree
);
909 printf(_("Wonderful.\n"));
911 parent
->next
= xmalloc(sizeof(*parent
->next
));
912 parent
->next
->item
= remoteheads
->item
;
913 parent
->next
->next
= NULL
;
915 commit_tree(merge_msg
.buf
, result_tree
, parent
, result_commit
, NULL
,
917 finish(head
, result_commit
, "In-index merge");
922 static int finish_automerge(struct commit
*head
,
923 struct commit_list
*common
,
924 unsigned char *result_tree
,
925 const char *wt_strategy
)
927 struct commit_list
*parents
= NULL
, *j
;
928 struct strbuf buf
= STRBUF_INIT
;
929 unsigned char result_commit
[20];
931 free_commit_list(common
);
932 if (allow_fast_forward
) {
933 parents
= remoteheads
;
934 commit_list_insert(head
, &parents
);
935 parents
= reduce_heads(parents
);
937 struct commit_list
**pptr
= &parents
;
939 pptr
= &commit_list_insert(head
,
941 for (j
= remoteheads
; j
; j
= j
->next
)
942 pptr
= &commit_list_insert(j
->item
, pptr
)->next
;
944 strbuf_addch(&merge_msg
, '\n');
946 free_commit_list(remoteheads
);
947 commit_tree(merge_msg
.buf
, result_tree
, parents
, result_commit
,
949 strbuf_addf(&buf
, "Merge made by the '%s' strategy.", wt_strategy
);
950 finish(head
, result_commit
, buf
.buf
);
951 strbuf_release(&buf
);
956 static int suggest_conflicts(int renormalizing
)
961 fp
= fopen(git_path("MERGE_MSG"), "a");
963 die_errno(_("Could not open '%s' for writing"),
964 git_path("MERGE_MSG"));
965 fprintf(fp
, "\nConflicts:\n");
966 for (pos
= 0; pos
< active_nr
; pos
++) {
967 struct cache_entry
*ce
= active_cache
[pos
];
970 fprintf(fp
, "\t%s\n", ce
->name
);
971 while (pos
+ 1 < active_nr
&&
973 active_cache
[pos
+ 1]->name
))
978 rerere(allow_rerere_auto
);
979 printf(_("Automatic merge failed; "
980 "fix conflicts and then commit the result.\n"));
984 static struct commit
*is_old_style_invocation(int argc
, const char **argv
,
985 const unsigned char *head
)
987 struct commit
*second_token
= NULL
;
989 unsigned char second_sha1
[20];
991 if (get_sha1(argv
[1], second_sha1
))
993 second_token
= lookup_commit_reference_gently(second_sha1
, 0);
995 die(_("'%s' is not a commit"), argv
[1]);
996 if (hashcmp(second_token
->object
.sha1
, head
))
1002 static int evaluate_result(void)
1005 struct rev_info rev
;
1007 /* Check how many files differ. */
1008 init_revisions(&rev
, "");
1009 setup_revisions(0, NULL
, &rev
, NULL
);
1010 rev
.diffopt
.output_format
|=
1011 DIFF_FORMAT_CALLBACK
;
1012 rev
.diffopt
.format_callback
= count_diff_files
;
1013 rev
.diffopt
.format_callback_data
= &cnt
;
1014 run_diff_files(&rev
, 0);
1017 * Check how many unmerged entries are
1020 cnt
+= count_unmerged_entries();
1026 * Pretend as if the user told us to merge with the tracking
1027 * branch we have for the upstream of the current branch
1029 static int setup_with_upstream(const char ***argv
)
1031 struct branch
*branch
= branch_get(NULL
);
1036 die(_("No current branch."));
1037 if (!branch
->remote
)
1038 die(_("No remote for the current branch."));
1039 if (!branch
->merge_nr
)
1040 die(_("No default upstream defined for the current branch."));
1042 args
= xcalloc(branch
->merge_nr
+ 1, sizeof(char *));
1043 for (i
= 0; i
< branch
->merge_nr
; i
++) {
1044 if (!branch
->merge
[i
]->dst
)
1045 die(_("No remote tracking branch for %s from %s"),
1046 branch
->merge
[i
]->src
, branch
->remote_name
);
1047 args
[i
] = branch
->merge
[i
]->dst
;
1054 static void write_merge_state(void)
1057 struct commit_list
*j
;
1058 struct strbuf buf
= STRBUF_INIT
;
1060 for (j
= remoteheads
; j
; j
= j
->next
) {
1061 unsigned const char *sha1
;
1062 struct commit
*c
= j
->item
;
1063 if (c
->util
&& merge_remote_util(c
)->obj
) {
1064 sha1
= merge_remote_util(c
)->obj
->sha1
;
1066 sha1
= c
->object
.sha1
;
1068 strbuf_addf(&buf
, "%s\n", sha1_to_hex(sha1
));
1070 fd
= open(git_path("MERGE_HEAD"), O_WRONLY
| O_CREAT
, 0666);
1072 die_errno(_("Could not open '%s' for writing"),
1073 git_path("MERGE_HEAD"));
1074 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1075 die_errno(_("Could not write to '%s'"), git_path("MERGE_HEAD"));
1077 strbuf_addch(&merge_msg
, '\n');
1078 write_merge_msg(&merge_msg
);
1079 fd
= open(git_path("MERGE_MODE"), O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
1081 die_errno(_("Could not open '%s' for writing"),
1082 git_path("MERGE_MODE"));
1084 if (!allow_fast_forward
)
1085 strbuf_addf(&buf
, "no-ff");
1086 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1087 die_errno(_("Could not write to '%s'"), git_path("MERGE_MODE"));
1091 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
1093 unsigned char result_tree
[20];
1094 unsigned char stash
[20];
1095 unsigned char head_sha1
[20];
1096 struct commit
*head_commit
;
1097 struct strbuf buf
= STRBUF_INIT
;
1098 const char *head_arg
;
1100 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
1101 struct commit_list
*common
= NULL
;
1102 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
1103 struct commit_list
**remotes
= &remoteheads
;
1105 if (argc
== 2 && !strcmp(argv
[1], "-h"))
1106 usage_with_options(builtin_merge_usage
, builtin_merge_options
);
1109 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1112 branch
= resolve_ref("HEAD", head_sha1
, 0, &flag
);
1113 if (branch
&& !prefixcmp(branch
, "refs/heads/"))
1115 if (!branch
|| is_null_sha1(head_sha1
))
1118 head_commit
= lookup_commit_or_die(head_sha1
, "HEAD");
1120 git_config(git_merge_config
, NULL
);
1122 if (branch_mergeoptions
)
1123 parse_branch_merge_options(branch_mergeoptions
);
1124 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
1125 builtin_merge_usage
, 0);
1127 if (verbosity
< 0 && show_progress
== -1)
1130 if (abort_current_merge
) {
1132 const char *nargv
[] = {"reset", "--merge", NULL
};
1134 if (!file_exists(git_path("MERGE_HEAD")))
1135 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1137 /* Invoke 'git reset --merge' */
1138 return cmd_reset(nargc
, nargv
, prefix
);
1141 if (read_cache_unmerged())
1142 die_resolve_conflict("merge");
1144 if (file_exists(git_path("MERGE_HEAD"))) {
1146 * There is no unmerged entry, don't advise 'git
1147 * add/rm <file>', just 'git commit'.
1149 if (advice_resolve_conflict
)
1150 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1151 "Please, commit your changes before you can merge."));
1153 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1155 if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
1156 if (advice_resolve_conflict
)
1157 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1158 "Please, commit your changes before you can merge."));
1160 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1162 resolve_undo_clear();
1168 if (!allow_fast_forward
)
1169 die(_("You cannot combine --squash with --no-ff."));
1173 if (!allow_fast_forward
&& fast_forward_only
)
1174 die(_("You cannot combine --no-ff with --ff-only."));
1176 if (!abort_current_merge
) {
1177 if (!argc
&& default_to_upstream
)
1178 argc
= setup_with_upstream(&argv
);
1179 else if (argc
== 1 && !strcmp(argv
[0], "-"))
1183 usage_with_options(builtin_merge_usage
,
1184 builtin_merge_options
);
1187 * This could be traditional "merge <msg> HEAD <commit>..." and
1188 * the way we can tell it is to see if the second token is HEAD,
1189 * but some people might have misused the interface and used a
1190 * committish that is the same as HEAD there instead.
1191 * Traditional format never would have "-m" so it is an
1192 * additional safety measure to check for it.
1195 if (!have_message
&& head_commit
&&
1196 is_old_style_invocation(argc
, argv
, head_commit
->object
.sha1
)) {
1197 strbuf_addstr(&merge_msg
, argv
[0]);
1201 } else if (!head_commit
) {
1202 struct commit
*remote_head
;
1204 * If the merged head is a valid one there is no reason
1205 * to forbid "git merge" into a branch yet to be born.
1206 * We do the same for "git pull".
1209 die(_("Can merge only exactly one commit into "
1212 die(_("Squash commit into empty head not supported yet"));
1213 if (!allow_fast_forward
)
1214 die(_("Non-fast-forward commit does not make sense into "
1216 remote_head
= get_merge_parent(argv
[0]);
1218 die(_("%s - not something we can merge"), argv
[0]);
1219 read_empty(remote_head
->object
.sha1
, 0);
1220 update_ref("initial pull", "HEAD", remote_head
->object
.sha1
,
1221 NULL
, 0, DIE_ON_ERR
);
1224 struct strbuf merge_names
= STRBUF_INIT
;
1226 /* We are invoked directly as the first-class UI. */
1230 * All the rest are the commits being merged; prepare
1231 * the standard merge summary message to be appended
1232 * to the given message.
1234 for (i
= 0; i
< argc
; i
++)
1235 merge_name(argv
[i
], &merge_names
);
1237 if (!have_message
|| shortlog_len
) {
1238 struct fmt_merge_msg_opts opts
;
1239 memset(&opts
, 0, sizeof(opts
));
1240 opts
.add_title
= !have_message
;
1241 opts
.shortlog_len
= shortlog_len
;
1243 fmt_merge_msg(&merge_names
, &merge_msg
, &opts
);
1245 strbuf_setlen(&merge_msg
, merge_msg
.len
- 1);
1249 if (!head_commit
|| !argc
)
1250 usage_with_options(builtin_merge_usage
,
1251 builtin_merge_options
);
1253 strbuf_addstr(&buf
, "merge");
1254 for (i
= 0; i
< argc
; i
++)
1255 strbuf_addf(&buf
, " %s", argv
[i
]);
1256 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
1259 for (i
= 0; i
< argc
; i
++) {
1260 struct commit
*commit
= get_merge_parent(argv
[i
]);
1262 die(_("%s - not something we can merge"), argv
[i
]);
1263 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1264 strbuf_addf(&buf
, "GITHEAD_%s",
1265 sha1_to_hex(commit
->object
.sha1
));
1266 setenv(buf
.buf
, argv
[i
], 1);
1268 if (merge_remote_util(commit
) &&
1269 merge_remote_util(commit
)->obj
&&
1270 merge_remote_util(commit
)->obj
->type
== OBJ_TAG
) {
1272 allow_fast_forward
= 0;
1276 if (!use_strategies
) {
1277 if (!remoteheads
->next
)
1278 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
1280 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
1283 for (i
= 0; i
< use_strategies_nr
; i
++) {
1284 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
1285 allow_fast_forward
= 0;
1286 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
1290 if (!remoteheads
->next
)
1291 common
= get_merge_bases(head_commit
, remoteheads
->item
, 1);
1293 struct commit_list
*list
= remoteheads
;
1294 commit_list_insert(head_commit
, &list
);
1295 common
= get_octopus_merge_bases(list
);
1299 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head_commit
->object
.sha1
,
1300 NULL
, 0, DIE_ON_ERR
);
1303 ; /* No common ancestors found. We need a real merge. */
1304 else if (!remoteheads
->next
&& !common
->next
&&
1305 common
->item
== remoteheads
->item
) {
1307 * If head can reach all the merge then we are up to date.
1308 * but first the most common case of merging one remote.
1310 finish_up_to_date("Already up-to-date.");
1312 } else if (allow_fast_forward
&& !remoteheads
->next
&&
1314 !hashcmp(common
->item
->object
.sha1
, head_commit
->object
.sha1
)) {
1315 /* Again the most common case of merging one remote. */
1316 struct strbuf msg
= STRBUF_INIT
;
1317 struct commit
*commit
;
1320 strcpy(hex
, find_unique_abbrev(head_commit
->object
.sha1
, DEFAULT_ABBREV
));
1323 printf(_("Updating %s..%s\n"),
1325 find_unique_abbrev(remoteheads
->item
->object
.sha1
,
1327 strbuf_addstr(&msg
, "Fast-forward");
1330 " (no commit created; -m option ignored)");
1331 commit
= remoteheads
->item
;
1335 if (checkout_fast_forward(head_commit
->object
.sha1
,
1336 commit
->object
.sha1
))
1339 finish(head_commit
, commit
->object
.sha1
, msg
.buf
);
1342 } else if (!remoteheads
->next
&& common
->next
)
1345 * We are not doing octopus and not fast-forward. Need
1348 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1350 * We are not doing octopus, not fast-forward, and have
1353 refresh_cache(REFRESH_QUIET
);
1354 if (allow_trivial
&& !fast_forward_only
) {
1355 /* See if it is really trivial. */
1356 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1357 printf(_("Trying really trivial in-index merge...\n"));
1358 if (!read_tree_trivial(common
->item
->object
.sha1
,
1359 head_commit
->object
.sha1
, remoteheads
->item
->object
.sha1
))
1360 return merge_trivial(head_commit
);
1361 printf(_("Nope.\n"));
1365 * An octopus. If we can reach all the remote we are up
1369 struct commit_list
*j
;
1371 for (j
= remoteheads
; j
; j
= j
->next
) {
1372 struct commit_list
*common_one
;
1375 * Here we *have* to calculate the individual
1376 * merge_bases again, otherwise "git merge HEAD^
1377 * HEAD^^" would be missed.
1379 common_one
= get_merge_bases(head_commit
, j
->item
, 1);
1380 if (hashcmp(common_one
->item
->object
.sha1
,
1381 j
->item
->object
.sha1
)) {
1387 finish_up_to_date("Already up-to-date. Yeeah!");
1392 if (fast_forward_only
)
1393 die(_("Not possible to fast-forward, aborting."));
1395 /* We are going to make a new commit. */
1396 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1399 * At this point, we need a real merge. No matter what strategy
1400 * we use, it would operate on the index, possibly affecting the
1401 * working tree, and when resolved cleanly, have the desired
1402 * tree in the index -- this means that the index must be in
1403 * sync with the head commit. The strategies are responsible
1406 if (use_strategies_nr
== 1 ||
1408 * Stash away the local changes so that we can try more than one.
1411 hashcpy(stash
, null_sha1
);
1413 for (i
= 0; i
< use_strategies_nr
; i
++) {
1416 printf(_("Rewinding the tree to pristine...\n"));
1417 restore_state(head_commit
->object
.sha1
, stash
);
1419 if (use_strategies_nr
!= 1)
1420 printf(_("Trying merge strategy %s...\n"),
1421 use_strategies
[i
]->name
);
1423 * Remember which strategy left the state in the working
1426 wt_strategy
= use_strategies
[i
]->name
;
1428 ret
= try_merge_strategy(use_strategies
[i
]->name
,
1429 common
, head_commit
, head_arg
);
1430 if (!option_commit
&& !ret
) {
1433 * This is necessary here just to avoid writing
1434 * the tree, but later we will *not* exit with
1435 * status code 1 because merge_was_ok is set.
1442 * The backend exits with 1 when conflicts are
1443 * left to be resolved, with 2 when it does not
1444 * handle the given merge at all.
1447 int cnt
= evaluate_result();
1449 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1450 best_strategy
= use_strategies
[i
]->name
;
1460 /* Automerge succeeded. */
1461 write_tree_trivial(result_tree
);
1462 automerge_was_ok
= 1;
1467 * If we have a resulting tree, that means the strategy module
1468 * auto resolved the merge cleanly.
1470 if (automerge_was_ok
)
1471 return finish_automerge(head_commit
, common
, result_tree
,
1475 * Pick the result from the best strategy and have the user fix
1478 if (!best_strategy
) {
1479 restore_state(head_commit
->object
.sha1
, stash
);
1480 if (use_strategies_nr
> 1)
1482 _("No merge strategy handled the merge.\n"));
1484 fprintf(stderr
, _("Merge with strategy %s failed.\n"),
1485 use_strategies
[0]->name
);
1487 } else if (best_strategy
== wt_strategy
)
1488 ; /* We already have its result in the working tree. */
1490 printf(_("Rewinding the tree to pristine...\n"));
1491 restore_state(head_commit
->object
.sha1
, stash
);
1492 printf(_("Using the %s to prepare resolving by hand.\n"),
1494 try_merge_strategy(best_strategy
, common
, head_commit
, head_arg
);
1498 finish(head_commit
, NULL
, NULL
);
1500 write_merge_state();
1503 fprintf(stderr
, _("Automatic merge went well; "
1504 "stopped before committing as requested\n"));
1507 return suggest_conflicts(option_renormalize
);