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 "fmt-merge-msg.h"
30 #include "gpg-interface.h"
32 #define DEFAULT_TWOHEAD (1<<0)
33 #define DEFAULT_OCTOPUS (1<<1)
34 #define NO_FAST_FORWARD (1<<2)
35 #define NO_TRIVIAL (1<<3)
42 static const char * const builtin_merge_usage
[] = {
43 N_("git merge [options] [<commit>...]"),
44 N_("git merge [options] <msg> HEAD <commit>"),
45 N_("git merge --abort"),
49 static int show_diffstat
= 1, shortlog_len
= -1, squash
;
50 static int option_commit
= 1, allow_fast_forward
= 1;
51 static int fast_forward_only
, option_edit
= -1;
52 static int allow_trivial
= 1, have_message
, verify_signatures
;
53 static int overwrite_ignore
= 1;
54 static struct strbuf merge_msg
= STRBUF_INIT
;
55 static struct strategy
**use_strategies
;
56 static size_t use_strategies_nr
, use_strategies_alloc
;
57 static const char **xopts
;
58 static size_t xopts_nr
, xopts_alloc
;
59 static const char *branch
;
60 static char *branch_mergeoptions
;
61 static int option_renormalize
;
63 static int allow_rerere_auto
;
64 static int abort_current_merge
;
65 static int show_progress
= -1;
66 static int default_to_upstream
;
67 static const char *sign_commit
;
69 static struct strategy all_strategy
[] = {
70 { "recursive", DEFAULT_TWOHEAD
| NO_TRIVIAL
},
71 { "octopus", DEFAULT_OCTOPUS
},
73 { "ours", NO_FAST_FORWARD
| NO_TRIVIAL
},
74 { "subtree", NO_FAST_FORWARD
| NO_TRIVIAL
},
77 static const char *pull_twohead
, *pull_octopus
;
79 static int option_parse_message(const struct option
*opt
,
80 const char *arg
, int unset
)
82 struct strbuf
*buf
= opt
->value
;
85 strbuf_setlen(buf
, 0);
87 strbuf_addf(buf
, "%s%s", buf
->len
? "\n\n" : "", arg
);
90 return error(_("switch `m' requires a value"));
94 static struct strategy
*get_strategy(const char *name
)
98 static struct cmdnames main_cmds
, other_cmds
;
104 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
105 if (!strcmp(name
, all_strategy
[i
].name
))
106 return &all_strategy
[i
];
109 struct cmdnames not_strategies
;
112 memset(¬_strategies
, 0, sizeof(struct cmdnames
));
113 load_command_list("git-merge-", &main_cmds
, &other_cmds
);
114 for (i
= 0; i
< main_cmds
.cnt
; i
++) {
116 struct cmdname
*ent
= main_cmds
.names
[i
];
117 for (j
= 0; j
< ARRAY_SIZE(all_strategy
); j
++)
118 if (!strncmp(ent
->name
, all_strategy
[j
].name
, ent
->len
)
119 && !all_strategy
[j
].name
[ent
->len
])
122 add_cmdname(¬_strategies
, ent
->name
, ent
->len
);
124 exclude_cmds(&main_cmds
, ¬_strategies
);
126 if (!is_in_cmdlist(&main_cmds
, name
) && !is_in_cmdlist(&other_cmds
, name
)) {
127 fprintf(stderr
, _("Could not find merge strategy '%s'.\n"), name
);
128 fprintf(stderr
, _("Available strategies are:"));
129 for (i
= 0; i
< main_cmds
.cnt
; i
++)
130 fprintf(stderr
, " %s", main_cmds
.names
[i
]->name
);
131 fprintf(stderr
, ".\n");
132 if (other_cmds
.cnt
) {
133 fprintf(stderr
, _("Available custom strategies are:"));
134 for (i
= 0; i
< other_cmds
.cnt
; i
++)
135 fprintf(stderr
, " %s", other_cmds
.names
[i
]->name
);
136 fprintf(stderr
, ".\n");
141 ret
= xcalloc(1, sizeof(struct strategy
));
142 ret
->name
= xstrdup(name
);
143 ret
->attr
= NO_TRIVIAL
;
147 static void append_strategy(struct strategy
*s
)
149 ALLOC_GROW(use_strategies
, use_strategies_nr
+ 1, use_strategies_alloc
);
150 use_strategies
[use_strategies_nr
++] = s
;
153 static int option_parse_strategy(const struct option
*opt
,
154 const char *name
, int unset
)
159 append_strategy(get_strategy(name
));
163 static int option_parse_x(const struct option
*opt
,
164 const char *arg
, int unset
)
169 ALLOC_GROW(xopts
, xopts_nr
+ 1, xopts_alloc
);
170 xopts
[xopts_nr
++] = xstrdup(arg
);
174 static int option_parse_n(const struct option
*opt
,
175 const char *arg
, int unset
)
177 show_diffstat
= unset
;
181 static struct option builtin_merge_options
[] = {
182 { OPTION_CALLBACK
, 'n', NULL
, NULL
, NULL
,
183 N_("do not show a diffstat at the end of the merge"),
184 PARSE_OPT_NOARG
, option_parse_n
},
185 OPT_BOOLEAN(0, "stat", &show_diffstat
,
186 N_("show a diffstat at the end of the merge")),
187 OPT_BOOLEAN(0, "summary", &show_diffstat
, N_("(synonym to --stat)")),
188 { OPTION_INTEGER
, 0, "log", &shortlog_len
, N_("n"),
189 N_("add (at most <n>) entries from shortlog to merge commit message"),
190 PARSE_OPT_OPTARG
, NULL
, DEFAULT_MERGE_LOG_LEN
},
191 OPT_BOOLEAN(0, "squash", &squash
,
192 N_("create a single commit instead of doing a merge")),
193 OPT_BOOLEAN(0, "commit", &option_commit
,
194 N_("perform a commit if the merge succeeds (default)")),
195 OPT_BOOL('e', "edit", &option_edit
,
196 N_("edit message before committing")),
197 OPT_BOOLEAN(0, "ff", &allow_fast_forward
,
198 N_("allow fast-forward (default)")),
199 OPT_BOOLEAN(0, "ff-only", &fast_forward_only
,
200 N_("abort if fast-forward is not possible")),
201 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto
),
202 OPT_BOOL(0, "verify-signatures", &verify_signatures
,
203 N_("Verify that the named commit has a valid GPG signature")),
204 OPT_CALLBACK('s', "strategy", &use_strategies
, N_("strategy"),
205 N_("merge strategy to use"), option_parse_strategy
),
206 OPT_CALLBACK('X', "strategy-option", &xopts
, N_("option=value"),
207 N_("option for selected merge strategy"), option_parse_x
),
208 OPT_CALLBACK('m', "message", &merge_msg
, N_("message"),
209 N_("merge commit message (for a non-fast-forward merge)"),
210 option_parse_message
),
211 OPT__VERBOSITY(&verbosity
),
212 OPT_BOOLEAN(0, "abort", &abort_current_merge
,
213 N_("abort the current in-progress merge")),
214 OPT_SET_INT(0, "progress", &show_progress
, N_("force progress reporting"), 1),
215 { OPTION_STRING
, 'S', "gpg-sign", &sign_commit
, N_("key id"),
216 N_("GPG sign commit"), PARSE_OPT_OPTARG
, NULL
, (intptr_t) "" },
217 OPT_BOOLEAN(0, "overwrite-ignore", &overwrite_ignore
, N_("update ignored files (default)")),
221 /* Cleans up metadata that is uninteresting after a succeeded merge. */
222 static void drop_save(void)
224 unlink(git_path("MERGE_HEAD"));
225 unlink(git_path("MERGE_MSG"));
226 unlink(git_path("MERGE_MODE"));
229 static int save_state(unsigned char *stash
)
232 struct child_process cp
;
233 struct strbuf buffer
= STRBUF_INIT
;
234 const char *argv
[] = {"stash", "create", NULL
};
236 memset(&cp
, 0, sizeof(cp
));
241 if (start_command(&cp
))
242 die(_("could not run stash."));
243 len
= strbuf_read(&buffer
, cp
.out
, 1024);
246 if (finish_command(&cp
) || len
< 0)
247 die(_("stash failed"));
248 else if (!len
) /* no changes */
250 strbuf_setlen(&buffer
, buffer
.len
-1);
251 if (get_sha1(buffer
.buf
, stash
))
252 die(_("not a valid object: %s"), buffer
.buf
);
256 static void read_empty(unsigned const char *sha1
, int verbose
)
261 args
[i
++] = "read-tree";
266 args
[i
++] = EMPTY_TREE_SHA1_HEX
;
267 args
[i
++] = sha1_to_hex(sha1
);
270 if (run_command_v_opt(args
, RUN_GIT_CMD
))
271 die(_("read-tree failed"));
274 static void reset_hard(unsigned const char *sha1
, int verbose
)
279 args
[i
++] = "read-tree";
282 args
[i
++] = "--reset";
284 args
[i
++] = sha1_to_hex(sha1
);
287 if (run_command_v_opt(args
, RUN_GIT_CMD
))
288 die(_("read-tree failed"));
291 static void restore_state(const unsigned char *head
,
292 const unsigned char *stash
)
294 struct strbuf sb
= STRBUF_INIT
;
295 const char *args
[] = { "stash", "apply", NULL
, NULL
};
297 if (is_null_sha1(stash
))
302 args
[2] = sha1_to_hex(stash
);
305 * It is OK to ignore error here, for example when there was
306 * nothing to restore.
308 run_command_v_opt(args
, RUN_GIT_CMD
);
311 refresh_cache(REFRESH_QUIET
);
314 /* This is called when no merge was necessary. */
315 static void finish_up_to_date(const char *msg
)
318 printf("%s%s\n", squash
? _(" (nothing to squash)") : "", msg
);
322 static void squash_message(struct commit
*commit
, struct commit_list
*remoteheads
)
325 struct strbuf out
= STRBUF_INIT
;
326 struct commit_list
*j
;
327 const char *filename
;
329 struct pretty_print_context ctx
= {0};
331 printf(_("Squash commit -- not updating HEAD\n"));
332 filename
= git_path("SQUASH_MSG");
333 fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
335 die_errno(_("Could not write to '%s'"), filename
);
337 init_revisions(&rev
, NULL
);
338 rev
.ignore_merges
= 1;
339 rev
.commit_format
= CMIT_FMT_MEDIUM
;
341 commit
->object
.flags
|= UNINTERESTING
;
342 add_pending_object(&rev
, &commit
->object
, NULL
);
344 for (j
= remoteheads
; j
; j
= j
->next
)
345 add_pending_object(&rev
, &j
->item
->object
, NULL
);
347 setup_revisions(0, NULL
, &rev
, NULL
);
348 if (prepare_revision_walk(&rev
))
349 die(_("revision walk setup failed"));
351 ctx
.abbrev
= rev
.abbrev
;
352 ctx
.date_mode
= rev
.date_mode
;
353 ctx
.fmt
= rev
.commit_format
;
355 strbuf_addstr(&out
, "Squashed commit of the following:\n");
356 while ((commit
= get_revision(&rev
)) != NULL
) {
357 strbuf_addch(&out
, '\n');
358 strbuf_addf(&out
, "commit %s\n",
359 sha1_to_hex(commit
->object
.sha1
));
360 pretty_print_commit(&ctx
, commit
, &out
);
362 if (write(fd
, out
.buf
, out
.len
) < 0)
363 die_errno(_("Writing SQUASH_MSG"));
365 die_errno(_("Finishing SQUASH_MSG"));
366 strbuf_release(&out
);
369 static void finish(struct commit
*head_commit
,
370 struct commit_list
*remoteheads
,
371 const unsigned char *new_head
, const char *msg
)
373 struct strbuf reflog_message
= STRBUF_INIT
;
374 const unsigned char *head
= head_commit
->object
.sha1
;
377 strbuf_addstr(&reflog_message
, getenv("GIT_REFLOG_ACTION"));
381 strbuf_addf(&reflog_message
, "%s: %s",
382 getenv("GIT_REFLOG_ACTION"), msg
);
385 squash_message(head_commit
, remoteheads
);
387 if (verbosity
>= 0 && !merge_msg
.len
)
388 printf(_("No merge message -- not updating HEAD\n"));
390 const char *argv_gc_auto
[] = { "gc", "--auto", NULL
};
391 update_ref(reflog_message
.buf
, "HEAD",
395 * We ignore errors in 'gc --auto', since the
396 * user should see them.
398 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
401 if (new_head
&& show_diffstat
) {
402 struct diff_options opts
;
404 opts
.stat_width
= -1; /* use full terminal width */
405 opts
.stat_graph_width
= -1; /* respect statGraphWidth config */
406 opts
.output_format
|=
407 DIFF_FORMAT_SUMMARY
| DIFF_FORMAT_DIFFSTAT
;
408 opts
.detect_rename
= DIFF_DETECT_RENAME
;
409 diff_setup_done(&opts
);
410 diff_tree_sha1(head
, new_head
, "", &opts
);
415 /* Run a post-merge hook */
416 run_hook(NULL
, "post-merge", squash
? "1" : "0", NULL
);
418 strbuf_release(&reflog_message
);
421 /* Get the name for the merge commit's message. */
422 static void merge_name(const char *remote
, struct strbuf
*msg
)
424 struct commit
*remote_head
;
425 unsigned char branch_head
[20];
426 struct strbuf buf
= STRBUF_INIT
;
427 struct strbuf bname
= STRBUF_INIT
;
432 strbuf_branchname(&bname
, remote
);
435 memset(branch_head
, 0, sizeof(branch_head
));
436 remote_head
= get_merge_parent(remote
);
438 die(_("'%s' does not point to a commit"), remote
);
440 if (dwim_ref(remote
, strlen(remote
), branch_head
, &found_ref
) > 0) {
441 if (!prefixcmp(found_ref
, "refs/heads/")) {
442 strbuf_addf(msg
, "%s\t\tbranch '%s' of .\n",
443 sha1_to_hex(branch_head
), remote
);
446 if (!prefixcmp(found_ref
, "refs/tags/")) {
447 strbuf_addf(msg
, "%s\t\ttag '%s' of .\n",
448 sha1_to_hex(branch_head
), remote
);
451 if (!prefixcmp(found_ref
, "refs/remotes/")) {
452 strbuf_addf(msg
, "%s\t\tremote-tracking branch '%s' of .\n",
453 sha1_to_hex(branch_head
), remote
);
458 /* See if remote matches <name>^^^.. or <name>~<number> */
459 for (len
= 0, ptr
= remote
+ strlen(remote
);
460 remote
< ptr
&& ptr
[-1] == '^';
467 ptr
= strrchr(remote
, '~');
469 int seen_nonzero
= 0;
472 while (*++ptr
&& isdigit(*ptr
)) {
473 seen_nonzero
|= (*ptr
!= '0');
477 len
= 0; /* not ...~<number> */
478 else if (seen_nonzero
)
481 early
= 1; /* "name~" is "name~1"! */
485 struct strbuf truname
= STRBUF_INIT
;
486 strbuf_addstr(&truname
, "refs/heads/");
487 strbuf_addstr(&truname
, remote
);
488 strbuf_setlen(&truname
, truname
.len
- len
);
489 if (ref_exists(truname
.buf
)) {
491 "%s\t\tbranch '%s'%s of .\n",
492 sha1_to_hex(remote_head
->object
.sha1
),
494 (early
? " (early part)" : ""));
495 strbuf_release(&truname
);
500 if (!strcmp(remote
, "FETCH_HEAD") &&
501 !access(git_path("FETCH_HEAD"), R_OK
)) {
502 const char *filename
;
504 struct strbuf line
= STRBUF_INIT
;
507 filename
= git_path("FETCH_HEAD");
508 fp
= fopen(filename
, "r");
510 die_errno(_("could not open '%s' for reading"),
512 strbuf_getline(&line
, fp
, '\n');
514 ptr
= strstr(line
.buf
, "\tnot-for-merge\t");
516 strbuf_remove(&line
, ptr
-line
.buf
+1, 13);
517 strbuf_addbuf(msg
, &line
);
518 strbuf_release(&line
);
521 strbuf_addf(msg
, "%s\t\tcommit '%s'\n",
522 sha1_to_hex(remote_head
->object
.sha1
), remote
);
524 strbuf_release(&buf
);
525 strbuf_release(&bname
);
528 static void parse_branch_merge_options(char *bmo
)
535 argc
= split_cmdline(bmo
, &argv
);
537 die(_("Bad branch.%s.mergeoptions string: %s"), branch
,
538 split_cmdline_strerror(argc
));
539 argv
= xrealloc(argv
, sizeof(*argv
) * (argc
+ 2));
540 memmove(argv
+ 1, argv
, sizeof(*argv
) * (argc
+ 1));
542 argv
[0] = "branch.*.mergeoptions";
543 parse_options(argc
, argv
, NULL
, builtin_merge_options
,
544 builtin_merge_usage
, 0);
548 static int git_merge_config(const char *k
, const char *v
, void *cb
)
552 if (branch
&& !prefixcmp(k
, "branch.") &&
553 !prefixcmp(k
+ 7, branch
) &&
554 !strcmp(k
+ 7 + strlen(branch
), ".mergeoptions")) {
555 free(branch_mergeoptions
);
556 branch_mergeoptions
= xstrdup(v
);
560 if (!strcmp(k
, "merge.diffstat") || !strcmp(k
, "merge.stat"))
561 show_diffstat
= git_config_bool(k
, v
);
562 else if (!strcmp(k
, "pull.twohead"))
563 return git_config_string(&pull_twohead
, k
, v
);
564 else if (!strcmp(k
, "pull.octopus"))
565 return git_config_string(&pull_octopus
, k
, v
);
566 else if (!strcmp(k
, "merge.renormalize"))
567 option_renormalize
= git_config_bool(k
, v
);
568 else if (!strcmp(k
, "merge.ff")) {
569 int boolval
= git_config_maybe_bool(k
, v
);
571 allow_fast_forward
= boolval
;
572 } else if (v
&& !strcmp(v
, "only")) {
573 allow_fast_forward
= 1;
574 fast_forward_only
= 1;
575 } /* do not barf on values from future versions of git */
577 } else if (!strcmp(k
, "merge.defaulttoupstream")) {
578 default_to_upstream
= git_config_bool(k
, v
);
582 status
= fmt_merge_msg_config(k
, v
, cb
);
585 status
= git_gpg_config(k
, v
, NULL
);
588 return git_diff_ui_config(k
, v
, cb
);
591 static int read_tree_trivial(unsigned char *common
, unsigned char *head
,
595 struct tree
*trees
[MAX_UNPACK_TREES
];
596 struct tree_desc t
[MAX_UNPACK_TREES
];
597 struct unpack_trees_options opts
;
599 memset(&opts
, 0, sizeof(opts
));
601 opts
.src_index
= &the_index
;
602 opts
.dst_index
= &the_index
;
604 opts
.verbose_update
= 1;
605 opts
.trivial_merges_only
= 1;
607 trees
[nr_trees
] = parse_tree_indirect(common
);
608 if (!trees
[nr_trees
++])
610 trees
[nr_trees
] = parse_tree_indirect(head
);
611 if (!trees
[nr_trees
++])
613 trees
[nr_trees
] = parse_tree_indirect(one
);
614 if (!trees
[nr_trees
++])
616 opts
.fn
= threeway_merge
;
617 cache_tree_free(&active_cache_tree
);
618 for (i
= 0; i
< nr_trees
; i
++) {
619 parse_tree(trees
[i
]);
620 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
622 if (unpack_trees(nr_trees
, t
, &opts
))
627 static void write_tree_trivial(unsigned char *sha1
)
629 if (write_cache_as_tree(sha1
, 0, NULL
))
630 die(_("git write-tree failed to write a tree"));
633 static int try_merge_strategy(const char *strategy
, struct commit_list
*common
,
634 struct commit_list
*remoteheads
,
635 struct commit
*head
, const char *head_arg
)
638 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
640 index_fd
= hold_locked_index(lock
, 1);
641 refresh_cache(REFRESH_QUIET
);
642 if (active_cache_changed
&&
643 (write_cache(index_fd
, active_cache
, active_nr
) ||
644 commit_locked_index(lock
)))
645 return error(_("Unable to write index."));
646 rollback_lock_file(lock
);
648 if (!strcmp(strategy
, "recursive") || !strcmp(strategy
, "subtree")) {
650 struct commit
*result
;
651 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
653 struct commit_list
*reversed
= NULL
;
654 struct merge_options o
;
655 struct commit_list
*j
;
657 if (remoteheads
->next
) {
658 error(_("Not handling anything other than two heads merge."));
662 init_merge_options(&o
);
663 if (!strcmp(strategy
, "subtree"))
664 o
.subtree_shift
= "";
666 o
.renormalize
= option_renormalize
;
667 o
.show_rename_progress
=
668 show_progress
== -1 ? isatty(2) : show_progress
;
670 for (x
= 0; x
< xopts_nr
; x
++)
671 if (parse_merge_opt(&o
, xopts
[x
]))
672 die(_("Unknown option for merge-recursive: -X%s"), xopts
[x
]);
674 o
.branch1
= head_arg
;
675 o
.branch2
= merge_remote_util(remoteheads
->item
)->name
;
677 for (j
= common
; j
; j
= j
->next
)
678 commit_list_insert(j
->item
, &reversed
);
680 index_fd
= hold_locked_index(lock
, 1);
681 clean
= merge_recursive(&o
, head
,
682 remoteheads
->item
, reversed
, &result
);
683 if (active_cache_changed
&&
684 (write_cache(index_fd
, active_cache
, active_nr
) ||
685 commit_locked_index(lock
)))
686 die (_("unable to write %s"), get_index_file());
687 rollback_lock_file(lock
);
688 return clean
? 0 : 1;
690 return try_merge_command(strategy
, xopts_nr
, xopts
,
691 common
, head_arg
, remoteheads
);
695 static void count_diff_files(struct diff_queue_struct
*q
,
696 struct diff_options
*opt
, void *data
)
703 static int count_unmerged_entries(void)
707 for (i
= 0; i
< active_nr
; i
++)
708 if (ce_stage(active_cache
[i
]))
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 void write_merge_msg(struct strbuf
*msg
)
760 const char *filename
= git_path("MERGE_MSG");
761 int fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
763 die_errno(_("Could not open '%s' for writing"),
765 if (write_in_full(fd
, msg
->buf
, msg
->len
) != msg
->len
)
766 die_errno(_("Could not write to '%s'"), filename
);
770 static void read_merge_msg(struct strbuf
*msg
)
772 const char *filename
= git_path("MERGE_MSG");
774 if (strbuf_read_file(msg
, filename
, 0) < 0)
775 die_errno(_("Could not read from '%s'"), filename
);
778 static void write_merge_state(struct commit_list
*);
779 static void abort_commit(struct commit_list
*remoteheads
, const char *err_msg
)
782 error("%s", err_msg
);
784 _("Not committing merge; use 'git commit' to complete the merge.\n"));
785 write_merge_state(remoteheads
);
789 static const char merge_editor_comment
[] =
790 N_("Please enter a commit message to explain why this merge is necessary,\n"
791 "especially if it merges an updated upstream into a topic branch.\n"
793 "Lines starting with '%c' will be ignored, and an empty message aborts\n"
796 static void prepare_to_commit(struct commit_list
*remoteheads
)
798 struct strbuf msg
= STRBUF_INIT
;
799 strbuf_addbuf(&msg
, &merge_msg
);
800 strbuf_addch(&msg
, '\n');
802 strbuf_commented_addf(&msg
, _(merge_editor_comment
), comment_line_char
);
803 write_merge_msg(&msg
);
804 if (run_hook(get_index_file(), "prepare-commit-msg",
805 git_path("MERGE_MSG"), "merge", NULL
, NULL
))
806 abort_commit(remoteheads
, NULL
);
807 if (0 < option_edit
) {
808 if (launch_editor(git_path("MERGE_MSG"), NULL
, NULL
))
809 abort_commit(remoteheads
, NULL
);
811 read_merge_msg(&msg
);
812 stripspace(&msg
, 0 < option_edit
);
814 abort_commit(remoteheads
, _("Empty commit message."));
815 strbuf_release(&merge_msg
);
816 strbuf_addbuf(&merge_msg
, &msg
);
817 strbuf_release(&msg
);
820 static int merge_trivial(struct commit
*head
, struct commit_list
*remoteheads
)
822 unsigned char result_tree
[20], result_commit
[20];
823 struct commit_list
*parent
= xmalloc(sizeof(*parent
));
825 write_tree_trivial(result_tree
);
826 printf(_("Wonderful.\n"));
828 parent
->next
= xmalloc(sizeof(*parent
->next
));
829 parent
->next
->item
= remoteheads
->item
;
830 parent
->next
->next
= NULL
;
831 prepare_to_commit(remoteheads
);
832 if (commit_tree(&merge_msg
, result_tree
, parent
, result_commit
, NULL
,
834 die(_("failed to write commit object"));
835 finish(head
, remoteheads
, result_commit
, "In-index merge");
840 static int finish_automerge(struct commit
*head
,
842 struct commit_list
*common
,
843 struct commit_list
*remoteheads
,
844 unsigned char *result_tree
,
845 const char *wt_strategy
)
847 struct commit_list
*parents
= NULL
;
848 struct strbuf buf
= STRBUF_INIT
;
849 unsigned char result_commit
[20];
851 free_commit_list(common
);
852 parents
= remoteheads
;
853 if (!head_subsumed
|| !allow_fast_forward
)
854 commit_list_insert(head
, &parents
);
855 strbuf_addch(&merge_msg
, '\n');
856 prepare_to_commit(remoteheads
);
857 if (commit_tree(&merge_msg
, result_tree
, parents
, result_commit
,
859 die(_("failed to write commit object"));
860 strbuf_addf(&buf
, "Merge made by the '%s' strategy.", wt_strategy
);
861 finish(head
, remoteheads
, result_commit
, buf
.buf
);
862 strbuf_release(&buf
);
867 static int suggest_conflicts(int renormalizing
)
869 const char *filename
;
873 filename
= git_path("MERGE_MSG");
874 fp
= fopen(filename
, "a");
876 die_errno(_("Could not open '%s' for writing"), filename
);
877 fprintf(fp
, "\nConflicts:\n");
878 for (pos
= 0; pos
< active_nr
; pos
++) {
879 struct cache_entry
*ce
= active_cache
[pos
];
882 fprintf(fp
, "\t%s\n", ce
->name
);
883 while (pos
+ 1 < active_nr
&&
885 active_cache
[pos
+ 1]->name
))
890 rerere(allow_rerere_auto
);
891 printf(_("Automatic merge failed; "
892 "fix conflicts and then commit the result.\n"));
896 static struct commit
*is_old_style_invocation(int argc
, const char **argv
,
897 const unsigned char *head
)
899 struct commit
*second_token
= NULL
;
901 unsigned char second_sha1
[20];
903 if (get_sha1(argv
[1], second_sha1
))
905 second_token
= lookup_commit_reference_gently(second_sha1
, 0);
907 die(_("'%s' is not a commit"), argv
[1]);
908 if (hashcmp(second_token
->object
.sha1
, head
))
914 static int evaluate_result(void)
919 /* Check how many files differ. */
920 init_revisions(&rev
, "");
921 setup_revisions(0, NULL
, &rev
, NULL
);
922 rev
.diffopt
.output_format
|=
923 DIFF_FORMAT_CALLBACK
;
924 rev
.diffopt
.format_callback
= count_diff_files
;
925 rev
.diffopt
.format_callback_data
= &cnt
;
926 run_diff_files(&rev
, 0);
929 * Check how many unmerged entries are
932 cnt
+= count_unmerged_entries();
938 * Pretend as if the user told us to merge with the tracking
939 * branch we have for the upstream of the current branch
941 static int setup_with_upstream(const char ***argv
)
943 struct branch
*branch
= branch_get(NULL
);
948 die(_("No current branch."));
950 die(_("No remote for the current branch."));
951 if (!branch
->merge_nr
)
952 die(_("No default upstream defined for the current branch."));
954 args
= xcalloc(branch
->merge_nr
+ 1, sizeof(char *));
955 for (i
= 0; i
< branch
->merge_nr
; i
++) {
956 if (!branch
->merge
[i
]->dst
)
957 die(_("No remote tracking branch for %s from %s"),
958 branch
->merge
[i
]->src
, branch
->remote_name
);
959 args
[i
] = branch
->merge
[i
]->dst
;
966 static void write_merge_state(struct commit_list
*remoteheads
)
968 const char *filename
;
970 struct commit_list
*j
;
971 struct strbuf buf
= STRBUF_INIT
;
973 for (j
= remoteheads
; j
; j
= j
->next
) {
974 unsigned const char *sha1
;
975 struct commit
*c
= j
->item
;
976 if (c
->util
&& merge_remote_util(c
)->obj
) {
977 sha1
= merge_remote_util(c
)->obj
->sha1
;
979 sha1
= c
->object
.sha1
;
981 strbuf_addf(&buf
, "%s\n", sha1_to_hex(sha1
));
983 filename
= git_path("MERGE_HEAD");
984 fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
986 die_errno(_("Could not open '%s' for writing"), filename
);
987 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
988 die_errno(_("Could not write to '%s'"), filename
);
990 strbuf_addch(&merge_msg
, '\n');
991 write_merge_msg(&merge_msg
);
993 filename
= git_path("MERGE_MODE");
994 fd
= open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
996 die_errno(_("Could not open '%s' for writing"), filename
);
998 if (!allow_fast_forward
)
999 strbuf_addf(&buf
, "no-ff");
1000 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1001 die_errno(_("Could not write to '%s'"), filename
);
1005 static int default_edit_option(void)
1007 static const char name
[] = "GIT_MERGE_AUTOEDIT";
1008 const char *e
= getenv(name
);
1009 struct stat st_stdin
, st_stdout
;
1012 /* an explicit -m msg without --[no-]edit */
1016 int v
= git_config_maybe_bool(name
, e
);
1018 die("Bad value '%s' in environment '%s'", e
, name
);
1022 /* Use editor if stdin and stdout are the same and is a tty */
1023 return (!fstat(0, &st_stdin
) &&
1024 !fstat(1, &st_stdout
) &&
1025 isatty(0) && isatty(1) &&
1026 st_stdin
.st_dev
== st_stdout
.st_dev
&&
1027 st_stdin
.st_ino
== st_stdout
.st_ino
&&
1028 st_stdin
.st_mode
== st_stdout
.st_mode
);
1031 static struct commit_list
*collect_parents(struct commit
*head_commit
,
1033 int argc
, const char **argv
)
1036 struct commit_list
*remoteheads
= NULL
, *parents
, *next
;
1037 struct commit_list
**remotes
= &remoteheads
;
1040 remotes
= &commit_list_insert(head_commit
, remotes
)->next
;
1041 for (i
= 0; i
< argc
; i
++) {
1042 struct commit
*commit
= get_merge_parent(argv
[i
]);
1044 die(_("%s - not something we can merge"), argv
[i
]);
1045 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1049 parents
= reduce_heads(remoteheads
);
1051 *head_subsumed
= 1; /* we will flip this to 0 when we find it */
1052 for (remoteheads
= NULL
, remotes
= &remoteheads
;
1055 struct commit
*commit
= parents
->item
;
1056 next
= parents
->next
;
1057 if (commit
== head_commit
)
1060 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1065 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
1067 unsigned char result_tree
[20];
1068 unsigned char stash
[20];
1069 unsigned char head_sha1
[20];
1070 struct commit
*head_commit
;
1071 struct strbuf buf
= STRBUF_INIT
;
1072 const char *head_arg
;
1073 int flag
, i
, ret
= 0, head_subsumed
;
1074 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
1075 struct commit_list
*common
= NULL
;
1076 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
1077 struct commit_list
*remoteheads
, *p
;
1078 void *branch_to_free
;
1080 if (argc
== 2 && !strcmp(argv
[1], "-h"))
1081 usage_with_options(builtin_merge_usage
, builtin_merge_options
);
1084 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1087 branch
= branch_to_free
= resolve_refdup("HEAD", head_sha1
, 0, &flag
);
1088 if (branch
&& !prefixcmp(branch
, "refs/heads/"))
1090 if (!branch
|| is_null_sha1(head_sha1
))
1093 head_commit
= lookup_commit_or_die(head_sha1
, "HEAD");
1095 git_config(git_merge_config
, NULL
);
1097 if (branch_mergeoptions
)
1098 parse_branch_merge_options(branch_mergeoptions
);
1099 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
1100 builtin_merge_usage
, 0);
1101 if (shortlog_len
< 0)
1102 shortlog_len
= (merge_log_config
> 0) ? merge_log_config
: 0;
1104 if (verbosity
< 0 && show_progress
== -1)
1107 if (abort_current_merge
) {
1109 const char *nargv
[] = {"reset", "--merge", NULL
};
1111 if (!file_exists(git_path("MERGE_HEAD")))
1112 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1114 /* Invoke 'git reset --merge' */
1115 ret
= cmd_reset(nargc
, nargv
, prefix
);
1119 if (read_cache_unmerged())
1120 die_resolve_conflict("merge");
1122 if (file_exists(git_path("MERGE_HEAD"))) {
1124 * There is no unmerged entry, don't advise 'git
1125 * add/rm <file>', just 'git commit'.
1127 if (advice_resolve_conflict
)
1128 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1129 "Please, commit your changes before you can merge."));
1131 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1133 if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
1134 if (advice_resolve_conflict
)
1135 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1136 "Please, commit your changes before you can merge."));
1138 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1140 resolve_undo_clear();
1146 if (!allow_fast_forward
)
1147 die(_("You cannot combine --squash with --no-ff."));
1151 if (!allow_fast_forward
&& fast_forward_only
)
1152 die(_("You cannot combine --no-ff with --ff-only."));
1154 if (!abort_current_merge
) {
1156 if (default_to_upstream
)
1157 argc
= setup_with_upstream(&argv
);
1159 die(_("No commit specified and merge.defaultToUpstream not set."));
1160 } else if (argc
== 1 && !strcmp(argv
[0], "-"))
1164 usage_with_options(builtin_merge_usage
,
1165 builtin_merge_options
);
1168 * This could be traditional "merge <msg> HEAD <commit>..." and
1169 * the way we can tell it is to see if the second token is HEAD,
1170 * but some people might have misused the interface and used a
1171 * committish that is the same as HEAD there instead.
1172 * Traditional format never would have "-m" so it is an
1173 * additional safety measure to check for it.
1176 if (!have_message
&& head_commit
&&
1177 is_old_style_invocation(argc
, argv
, head_commit
->object
.sha1
)) {
1178 strbuf_addstr(&merge_msg
, argv
[0]);
1182 remoteheads
= collect_parents(head_commit
, &head_subsumed
, argc
, argv
);
1183 } else if (!head_commit
) {
1184 struct commit
*remote_head
;
1186 * If the merged head is a valid one there is no reason
1187 * to forbid "git merge" into a branch yet to be born.
1188 * We do the same for "git pull".
1191 die(_("Can merge only exactly one commit into "
1194 die(_("Squash commit into empty head not supported yet"));
1195 if (!allow_fast_forward
)
1196 die(_("Non-fast-forward commit does not make sense into "
1198 remoteheads
= collect_parents(head_commit
, &head_subsumed
, argc
, argv
);
1199 remote_head
= remoteheads
->item
;
1201 die(_("%s - not something we can merge"), argv
[0]);
1202 read_empty(remote_head
->object
.sha1
, 0);
1203 update_ref("initial pull", "HEAD", remote_head
->object
.sha1
,
1204 NULL
, 0, DIE_ON_ERR
);
1207 struct strbuf merge_names
= STRBUF_INIT
;
1209 /* We are invoked directly as the first-class UI. */
1213 * All the rest are the commits being merged; prepare
1214 * the standard merge summary message to be appended
1215 * to the given message.
1217 remoteheads
= collect_parents(head_commit
, &head_subsumed
, argc
, argv
);
1218 for (p
= remoteheads
; p
; p
= p
->next
)
1219 merge_name(merge_remote_util(p
->item
)->name
, &merge_names
);
1221 if (!have_message
|| shortlog_len
) {
1222 struct fmt_merge_msg_opts opts
;
1223 memset(&opts
, 0, sizeof(opts
));
1224 opts
.add_title
= !have_message
;
1225 opts
.shortlog_len
= shortlog_len
;
1226 opts
.credit_people
= (0 < option_edit
);
1228 fmt_merge_msg(&merge_names
, &merge_msg
, &opts
);
1230 strbuf_setlen(&merge_msg
, merge_msg
.len
- 1);
1234 if (!head_commit
|| !argc
)
1235 usage_with_options(builtin_merge_usage
,
1236 builtin_merge_options
);
1238 if (verify_signatures
) {
1239 for (p
= remoteheads
; p
; p
= p
->next
) {
1240 struct commit
*commit
= p
->item
;
1242 struct signature_check signature_check
;
1243 memset(&signature_check
, 0, sizeof(signature_check
));
1245 check_commit_signature(commit
, &signature_check
);
1247 strcpy(hex
, find_unique_abbrev(commit
->object
.sha1
, DEFAULT_ABBREV
));
1248 switch (signature_check
.result
) {
1252 die(_("Commit %s has a bad GPG signature "
1253 "allegedly by %s."), hex
, signature_check
.signer
);
1255 die(_("Commit %s does not have a GPG signature."), hex
);
1257 if (verbosity
>= 0 && signature_check
.result
== 'G')
1258 printf(_("Commit %s has a good GPG signature by %s\n"),
1259 hex
, signature_check
.signer
);
1261 free(signature_check
.gpg_output
);
1262 free(signature_check
.gpg_status
);
1263 free(signature_check
.signer
);
1264 free(signature_check
.key
);
1268 strbuf_addstr(&buf
, "merge");
1269 for (p
= remoteheads
; p
; p
= p
->next
)
1270 strbuf_addf(&buf
, " %s", merge_remote_util(p
->item
)->name
);
1271 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
1274 for (p
= remoteheads
; p
; p
= p
->next
) {
1275 struct commit
*commit
= p
->item
;
1276 strbuf_addf(&buf
, "GITHEAD_%s",
1277 sha1_to_hex(commit
->object
.sha1
));
1278 setenv(buf
.buf
, merge_remote_util(commit
)->name
, 1);
1280 if (!fast_forward_only
&&
1281 merge_remote_util(commit
) &&
1282 merge_remote_util(commit
)->obj
&&
1283 merge_remote_util(commit
)->obj
->type
== OBJ_TAG
)
1284 allow_fast_forward
= 0;
1287 if (option_edit
< 0)
1288 option_edit
= default_edit_option();
1290 if (!use_strategies
) {
1292 ; /* already up-to-date */
1293 else if (!remoteheads
->next
)
1294 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
1296 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
1299 for (i
= 0; i
< use_strategies_nr
; i
++) {
1300 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
1301 allow_fast_forward
= 0;
1302 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
1307 ; /* already up-to-date */
1308 else if (!remoteheads
->next
)
1309 common
= get_merge_bases(head_commit
, remoteheads
->item
, 1);
1311 struct commit_list
*list
= remoteheads
;
1312 commit_list_insert(head_commit
, &list
);
1313 common
= get_octopus_merge_bases(list
);
1317 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head_commit
->object
.sha1
,
1318 NULL
, 0, DIE_ON_ERR
);
1320 if (remoteheads
&& !common
)
1321 ; /* No common ancestors found. We need a real merge. */
1322 else if (!remoteheads
||
1323 (!remoteheads
->next
&& !common
->next
&&
1324 common
->item
== remoteheads
->item
)) {
1326 * If head can reach all the merge then we are up to date.
1327 * but first the most common case of merging one remote.
1329 finish_up_to_date("Already up-to-date.");
1331 } else if (allow_fast_forward
&& !remoteheads
->next
&&
1333 !hashcmp(common
->item
->object
.sha1
, head_commit
->object
.sha1
)) {
1334 /* Again the most common case of merging one remote. */
1335 struct strbuf msg
= STRBUF_INIT
;
1336 struct commit
*commit
;
1339 strcpy(hex
, find_unique_abbrev(head_commit
->object
.sha1
, DEFAULT_ABBREV
));
1342 printf(_("Updating %s..%s\n"),
1344 find_unique_abbrev(remoteheads
->item
->object
.sha1
,
1346 strbuf_addstr(&msg
, "Fast-forward");
1349 " (no commit created; -m option ignored)");
1350 commit
= remoteheads
->item
;
1356 if (checkout_fast_forward(head_commit
->object
.sha1
,
1357 commit
->object
.sha1
,
1358 overwrite_ignore
)) {
1363 finish(head_commit
, remoteheads
, commit
->object
.sha1
, msg
.buf
);
1366 } else if (!remoteheads
->next
&& common
->next
)
1369 * We are not doing octopus and not fast-forward. Need
1372 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1374 * We are not doing octopus, not fast-forward, and have
1377 refresh_cache(REFRESH_QUIET
);
1378 if (allow_trivial
&& !fast_forward_only
) {
1379 /* See if it is really trivial. */
1380 git_committer_info(IDENT_STRICT
);
1381 printf(_("Trying really trivial in-index merge...\n"));
1382 if (!read_tree_trivial(common
->item
->object
.sha1
,
1383 head_commit
->object
.sha1
,
1384 remoteheads
->item
->object
.sha1
)) {
1385 ret
= merge_trivial(head_commit
, remoteheads
);
1388 printf(_("Nope.\n"));
1392 * An octopus. If we can reach all the remote we are up
1396 struct commit_list
*j
;
1398 for (j
= remoteheads
; j
; j
= j
->next
) {
1399 struct commit_list
*common_one
;
1402 * Here we *have* to calculate the individual
1403 * merge_bases again, otherwise "git merge HEAD^
1404 * HEAD^^" would be missed.
1406 common_one
= get_merge_bases(head_commit
, j
->item
, 1);
1407 if (hashcmp(common_one
->item
->object
.sha1
,
1408 j
->item
->object
.sha1
)) {
1414 finish_up_to_date("Already up-to-date. Yeeah!");
1419 if (fast_forward_only
)
1420 die(_("Not possible to fast-forward, aborting."));
1422 /* We are going to make a new commit. */
1423 git_committer_info(IDENT_STRICT
);
1426 * At this point, we need a real merge. No matter what strategy
1427 * we use, it would operate on the index, possibly affecting the
1428 * working tree, and when resolved cleanly, have the desired
1429 * tree in the index -- this means that the index must be in
1430 * sync with the head commit. The strategies are responsible
1433 if (use_strategies_nr
== 1 ||
1435 * Stash away the local changes so that we can try more than one.
1438 hashcpy(stash
, null_sha1
);
1440 for (i
= 0; i
< use_strategies_nr
; i
++) {
1443 printf(_("Rewinding the tree to pristine...\n"));
1444 restore_state(head_commit
->object
.sha1
, stash
);
1446 if (use_strategies_nr
!= 1)
1447 printf(_("Trying merge strategy %s...\n"),
1448 use_strategies
[i
]->name
);
1450 * Remember which strategy left the state in the working
1453 wt_strategy
= use_strategies
[i
]->name
;
1455 ret
= try_merge_strategy(use_strategies
[i
]->name
,
1456 common
, remoteheads
,
1457 head_commit
, head_arg
);
1458 if (!option_commit
&& !ret
) {
1461 * This is necessary here just to avoid writing
1462 * the tree, but later we will *not* exit with
1463 * status code 1 because merge_was_ok is set.
1470 * The backend exits with 1 when conflicts are
1471 * left to be resolved, with 2 when it does not
1472 * handle the given merge at all.
1475 int cnt
= evaluate_result();
1477 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1478 best_strategy
= use_strategies
[i
]->name
;
1488 /* Automerge succeeded. */
1489 write_tree_trivial(result_tree
);
1490 automerge_was_ok
= 1;
1495 * If we have a resulting tree, that means the strategy module
1496 * auto resolved the merge cleanly.
1498 if (automerge_was_ok
) {
1499 ret
= finish_automerge(head_commit
, head_subsumed
,
1500 common
, remoteheads
,
1501 result_tree
, wt_strategy
);
1506 * Pick the result from the best strategy and have the user fix
1509 if (!best_strategy
) {
1510 restore_state(head_commit
->object
.sha1
, stash
);
1511 if (use_strategies_nr
> 1)
1513 _("No merge strategy handled the merge.\n"));
1515 fprintf(stderr
, _("Merge with strategy %s failed.\n"),
1516 use_strategies
[0]->name
);
1519 } else if (best_strategy
== wt_strategy
)
1520 ; /* We already have its result in the working tree. */
1522 printf(_("Rewinding the tree to pristine...\n"));
1523 restore_state(head_commit
->object
.sha1
, stash
);
1524 printf(_("Using the %s to prepare resolving by hand.\n"),
1526 try_merge_strategy(best_strategy
, common
, remoteheads
,
1527 head_commit
, head_arg
);
1531 finish(head_commit
, remoteheads
, NULL
, NULL
);
1533 write_merge_state(remoteheads
);
1536 fprintf(stderr
, _("Automatic merge went well; "
1537 "stopped before committing as requested\n"));
1539 ret
= suggest_conflicts(option_renormalize
);
1542 free(branch_to_free
);