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"
30 #define DEFAULT_TWOHEAD (1<<0)
31 #define DEFAULT_OCTOPUS (1<<1)
32 #define NO_FAST_FORWARD (1<<2)
33 #define NO_TRIVIAL (1<<3)
40 static const char * const builtin_merge_usage
[] = {
41 "git merge [options] [<commit>...]",
42 "git merge [options] <msg> HEAD <commit>",
47 static int show_diffstat
= 1, shortlog_len
, squash
;
48 static int option_commit
= 1, allow_fast_forward
= 1;
49 static int fast_forward_only
, option_edit
;
50 static int allow_trivial
= 1, have_message
;
51 static struct strbuf merge_msg
;
52 static struct commit_list
*remoteheads
;
53 static struct strategy
**use_strategies
;
54 static size_t use_strategies_nr
, use_strategies_alloc
;
55 static const char **xopts
;
56 static size_t xopts_nr
, xopts_alloc
;
57 static const char *branch
;
58 static char *branch_mergeoptions
;
59 static int option_renormalize
;
61 static int allow_rerere_auto
;
62 static int abort_current_merge
;
63 static int show_progress
= -1;
64 static int default_to_upstream
;
66 static struct strategy all_strategy
[] = {
67 { "recursive", DEFAULT_TWOHEAD
| NO_TRIVIAL
},
68 { "octopus", DEFAULT_OCTOPUS
},
70 { "ours", NO_FAST_FORWARD
| NO_TRIVIAL
},
71 { "subtree", NO_FAST_FORWARD
| NO_TRIVIAL
},
74 static const char *pull_twohead
, *pull_octopus
;
76 static int option_parse_message(const struct option
*opt
,
77 const char *arg
, int unset
)
79 struct strbuf
*buf
= opt
->value
;
82 strbuf_setlen(buf
, 0);
84 strbuf_addf(buf
, "%s%s", buf
->len
? "\n\n" : "", arg
);
87 return error(_("switch `m' requires a value"));
91 static struct strategy
*get_strategy(const char *name
)
95 static struct cmdnames main_cmds
, other_cmds
;
101 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
102 if (!strcmp(name
, all_strategy
[i
].name
))
103 return &all_strategy
[i
];
106 struct cmdnames not_strategies
;
109 memset(¬_strategies
, 0, sizeof(struct cmdnames
));
110 load_command_list("git-merge-", &main_cmds
, &other_cmds
);
111 for (i
= 0; i
< main_cmds
.cnt
; i
++) {
113 struct cmdname
*ent
= main_cmds
.names
[i
];
114 for (j
= 0; j
< ARRAY_SIZE(all_strategy
); j
++)
115 if (!strncmp(ent
->name
, all_strategy
[j
].name
, ent
->len
)
116 && !all_strategy
[j
].name
[ent
->len
])
119 add_cmdname(¬_strategies
, ent
->name
, ent
->len
);
121 exclude_cmds(&main_cmds
, ¬_strategies
);
123 if (!is_in_cmdlist(&main_cmds
, name
) && !is_in_cmdlist(&other_cmds
, name
)) {
124 fprintf(stderr
, _("Could not find merge strategy '%s'.\n"), name
);
125 fprintf(stderr
, _("Available strategies are:"));
126 for (i
= 0; i
< main_cmds
.cnt
; i
++)
127 fprintf(stderr
, " %s", main_cmds
.names
[i
]->name
);
128 fprintf(stderr
, ".\n");
129 if (other_cmds
.cnt
) {
130 fprintf(stderr
, _("Available custom strategies are:"));
131 for (i
= 0; i
< other_cmds
.cnt
; i
++)
132 fprintf(stderr
, " %s", other_cmds
.names
[i
]->name
);
133 fprintf(stderr
, ".\n");
138 ret
= xcalloc(1, sizeof(struct strategy
));
139 ret
->name
= xstrdup(name
);
140 ret
->attr
= NO_TRIVIAL
;
144 static void append_strategy(struct strategy
*s
)
146 ALLOC_GROW(use_strategies
, use_strategies_nr
+ 1, use_strategies_alloc
);
147 use_strategies
[use_strategies_nr
++] = s
;
150 static int option_parse_strategy(const struct option
*opt
,
151 const char *name
, int unset
)
156 append_strategy(get_strategy(name
));
160 static int option_parse_x(const struct option
*opt
,
161 const char *arg
, int unset
)
166 ALLOC_GROW(xopts
, xopts_nr
+ 1, xopts_alloc
);
167 xopts
[xopts_nr
++] = xstrdup(arg
);
171 static int option_parse_n(const struct option
*opt
,
172 const char *arg
, int unset
)
174 show_diffstat
= unset
;
178 static struct option builtin_merge_options
[] = {
179 { OPTION_CALLBACK
, 'n', NULL
, NULL
, NULL
,
180 "do not show a diffstat at the end of the merge",
181 PARSE_OPT_NOARG
, option_parse_n
},
182 OPT_BOOLEAN(0, "stat", &show_diffstat
,
183 "show a diffstat at the end of the merge"),
184 OPT_BOOLEAN(0, "summary", &show_diffstat
, "(synonym to --stat)"),
185 { OPTION_INTEGER
, 0, "log", &shortlog_len
, "n",
186 "add (at most <n>) entries from shortlog to merge commit message",
187 PARSE_OPT_OPTARG
, NULL
, DEFAULT_MERGE_LOG_LEN
},
188 OPT_BOOLEAN(0, "squash", &squash
,
189 "create a single commit instead of doing a merge"),
190 OPT_BOOLEAN(0, "commit", &option_commit
,
191 "perform a commit if the merge succeeds (default)"),
192 OPT_BOOLEAN('e', "edit", &option_edit
,
193 "edit message before committing"),
194 OPT_BOOLEAN(0, "ff", &allow_fast_forward
,
195 "allow fast-forward (default)"),
196 OPT_BOOLEAN(0, "ff-only", &fast_forward_only
,
197 "abort if fast-forward is not possible"),
198 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto
),
199 OPT_CALLBACK('s', "strategy", &use_strategies
, "strategy",
200 "merge strategy to use", option_parse_strategy
),
201 OPT_CALLBACK('X', "strategy-option", &xopts
, "option=value",
202 "option for selected merge strategy", option_parse_x
),
203 OPT_CALLBACK('m', "message", &merge_msg
, "message",
204 "merge commit message (for a non-fast-forward merge)",
205 option_parse_message
),
206 OPT__VERBOSITY(&verbosity
),
207 OPT_BOOLEAN(0, "abort", &abort_current_merge
,
208 "abort the current in-progress merge"),
209 OPT_SET_INT(0, "progress", &show_progress
, "force progress reporting", 1),
213 /* Cleans up metadata that is uninteresting after a succeeded merge. */
214 static void drop_save(void)
216 unlink(git_path("MERGE_HEAD"));
217 unlink(git_path("MERGE_MSG"));
218 unlink(git_path("MERGE_MODE"));
221 static int save_state(unsigned char *stash
)
224 struct child_process cp
;
225 struct strbuf buffer
= STRBUF_INIT
;
226 const char *argv
[] = {"stash", "create", NULL
};
228 memset(&cp
, 0, sizeof(cp
));
233 if (start_command(&cp
))
234 die(_("could not run stash."));
235 len
= strbuf_read(&buffer
, cp
.out
, 1024);
238 if (finish_command(&cp
) || len
< 0)
239 die(_("stash failed"));
240 else if (!len
) /* no changes */
242 strbuf_setlen(&buffer
, buffer
.len
-1);
243 if (get_sha1(buffer
.buf
, stash
))
244 die(_("not a valid object: %s"), buffer
.buf
);
248 static void read_empty(unsigned const char *sha1
, int verbose
)
253 args
[i
++] = "read-tree";
258 args
[i
++] = EMPTY_TREE_SHA1_HEX
;
259 args
[i
++] = sha1_to_hex(sha1
);
262 if (run_command_v_opt(args
, RUN_GIT_CMD
))
263 die(_("read-tree failed"));
266 static void reset_hard(unsigned const char *sha1
, int verbose
)
271 args
[i
++] = "read-tree";
274 args
[i
++] = "--reset";
276 args
[i
++] = sha1_to_hex(sha1
);
279 if (run_command_v_opt(args
, RUN_GIT_CMD
))
280 die(_("read-tree failed"));
283 static void restore_state(const unsigned char *head
,
284 const unsigned char *stash
)
286 struct strbuf sb
= STRBUF_INIT
;
287 const char *args
[] = { "stash", "apply", NULL
, NULL
};
289 if (is_null_sha1(stash
))
294 args
[2] = sha1_to_hex(stash
);
297 * It is OK to ignore error here, for example when there was
298 * nothing to restore.
300 run_command_v_opt(args
, RUN_GIT_CMD
);
303 refresh_cache(REFRESH_QUIET
);
306 /* This is called when no merge was necessary. */
307 static void finish_up_to_date(const char *msg
)
310 printf("%s%s\n", squash
? _(" (nothing to squash)") : "", msg
);
314 static void squash_message(struct commit
*commit
)
317 struct strbuf out
= STRBUF_INIT
;
318 struct commit_list
*j
;
320 struct pretty_print_context ctx
= {0};
322 printf(_("Squash commit -- not updating HEAD\n"));
323 fd
= open(git_path("SQUASH_MSG"), O_WRONLY
| O_CREAT
, 0666);
325 die_errno(_("Could not write to '%s'"), git_path("SQUASH_MSG"));
327 init_revisions(&rev
, NULL
);
328 rev
.ignore_merges
= 1;
329 rev
.commit_format
= CMIT_FMT_MEDIUM
;
331 commit
->object
.flags
|= UNINTERESTING
;
332 add_pending_object(&rev
, &commit
->object
, NULL
);
334 for (j
= remoteheads
; j
; j
= j
->next
)
335 add_pending_object(&rev
, &j
->item
->object
, NULL
);
337 setup_revisions(0, NULL
, &rev
, NULL
);
338 if (prepare_revision_walk(&rev
))
339 die(_("revision walk setup failed"));
341 ctx
.abbrev
= rev
.abbrev
;
342 ctx
.date_mode
= rev
.date_mode
;
343 ctx
.fmt
= rev
.commit_format
;
345 strbuf_addstr(&out
, "Squashed commit of the following:\n");
346 while ((commit
= get_revision(&rev
)) != NULL
) {
347 strbuf_addch(&out
, '\n');
348 strbuf_addf(&out
, "commit %s\n",
349 sha1_to_hex(commit
->object
.sha1
));
350 pretty_print_commit(&ctx
, commit
, &out
);
352 if (write(fd
, out
.buf
, out
.len
) < 0)
353 die_errno(_("Writing SQUASH_MSG"));
355 die_errno(_("Finishing SQUASH_MSG"));
356 strbuf_release(&out
);
359 static void finish(struct commit
*head_commit
,
360 const unsigned char *new_head
, const char *msg
)
362 struct strbuf reflog_message
= STRBUF_INIT
;
363 const unsigned char *head
= head_commit
->object
.sha1
;
366 strbuf_addstr(&reflog_message
, getenv("GIT_REFLOG_ACTION"));
370 strbuf_addf(&reflog_message
, "%s: %s",
371 getenv("GIT_REFLOG_ACTION"), msg
);
374 squash_message(head_commit
);
376 if (verbosity
>= 0 && !merge_msg
.len
)
377 printf(_("No merge message -- not updating HEAD\n"));
379 const char *argv_gc_auto
[] = { "gc", "--auto", NULL
};
380 update_ref(reflog_message
.buf
, "HEAD",
384 * We ignore errors in 'gc --auto', since the
385 * user should see them.
387 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
390 if (new_head
&& show_diffstat
) {
391 struct diff_options opts
;
393 opts
.output_format
|=
394 DIFF_FORMAT_SUMMARY
| DIFF_FORMAT_DIFFSTAT
;
395 opts
.detect_rename
= DIFF_DETECT_RENAME
;
396 if (diff_setup_done(&opts
) < 0)
397 die(_("diff_setup_done failed"));
398 diff_tree_sha1(head
, new_head
, "", &opts
);
403 /* Run a post-merge hook */
404 run_hook(NULL
, "post-merge", squash
? "1" : "0", NULL
);
406 strbuf_release(&reflog_message
);
409 static struct object
*want_commit(const char *name
)
412 unsigned char sha1
[20];
413 if (get_sha1(name
, sha1
))
415 obj
= parse_object(sha1
);
416 return peel_to_type(name
, 0, obj
, OBJ_COMMIT
);
419 /* Get the name for the merge commit's message. */
420 static void merge_name(const char *remote
, struct strbuf
*msg
)
422 struct object
*remote_head
;
423 unsigned char branch_head
[20], buf_sha
[20];
424 struct strbuf buf
= STRBUF_INIT
;
425 struct strbuf bname
= STRBUF_INIT
;
430 strbuf_branchname(&bname
, remote
);
433 memset(branch_head
, 0, sizeof(branch_head
));
434 remote_head
= want_commit(remote
);
436 die(_("'%s' does not point to a commit"), remote
);
438 if (dwim_ref(remote
, strlen(remote
), branch_head
, &found_ref
) > 0) {
439 if (!prefixcmp(found_ref
, "refs/heads/")) {
440 strbuf_addf(msg
, "%s\t\tbranch '%s' of .\n",
441 sha1_to_hex(branch_head
), remote
);
444 if (!prefixcmp(found_ref
, "refs/remotes/")) {
445 strbuf_addf(msg
, "%s\t\tremote-tracking branch '%s' of .\n",
446 sha1_to_hex(branch_head
), remote
);
451 /* See if remote matches <name>^^^.. or <name>~<number> */
452 for (len
= 0, ptr
= remote
+ strlen(remote
);
453 remote
< ptr
&& ptr
[-1] == '^';
460 ptr
= strrchr(remote
, '~');
462 int seen_nonzero
= 0;
465 while (*++ptr
&& isdigit(*ptr
)) {
466 seen_nonzero
|= (*ptr
!= '0');
470 len
= 0; /* not ...~<number> */
471 else if (seen_nonzero
)
474 early
= 1; /* "name~" is "name~1"! */
478 struct strbuf truname
= STRBUF_INIT
;
479 strbuf_addstr(&truname
, "refs/heads/");
480 strbuf_addstr(&truname
, remote
);
481 strbuf_setlen(&truname
, truname
.len
- len
);
482 if (resolve_ref(truname
.buf
, buf_sha
, 1, NULL
)) {
484 "%s\t\tbranch '%s'%s of .\n",
485 sha1_to_hex(remote_head
->sha1
),
487 (early
? " (early part)" : ""));
488 strbuf_release(&truname
);
493 if (!strcmp(remote
, "FETCH_HEAD") &&
494 !access(git_path("FETCH_HEAD"), R_OK
)) {
496 struct strbuf line
= STRBUF_INIT
;
499 fp
= fopen(git_path("FETCH_HEAD"), "r");
501 die_errno(_("could not open '%s' for reading"),
502 git_path("FETCH_HEAD"));
503 strbuf_getline(&line
, fp
, '\n');
505 ptr
= strstr(line
.buf
, "\tnot-for-merge\t");
507 strbuf_remove(&line
, ptr
-line
.buf
+1, 13);
508 strbuf_addbuf(msg
, &line
);
509 strbuf_release(&line
);
512 strbuf_addf(msg
, "%s\t\tcommit '%s'\n",
513 sha1_to_hex(remote_head
->sha1
), remote
);
515 strbuf_release(&buf
);
516 strbuf_release(&bname
);
519 static void parse_branch_merge_options(char *bmo
)
526 argc
= split_cmdline(bmo
, &argv
);
528 die(_("Bad branch.%s.mergeoptions string: %s"), branch
,
529 split_cmdline_strerror(argc
));
530 argv
= xrealloc(argv
, sizeof(*argv
) * (argc
+ 2));
531 memmove(argv
+ 1, argv
, sizeof(*argv
) * (argc
+ 1));
533 argv
[0] = "branch.*.mergeoptions";
534 parse_options(argc
, argv
, NULL
, builtin_merge_options
,
535 builtin_merge_usage
, 0);
539 static int git_merge_config(const char *k
, const char *v
, void *cb
)
541 if (branch
&& !prefixcmp(k
, "branch.") &&
542 !prefixcmp(k
+ 7, branch
) &&
543 !strcmp(k
+ 7 + strlen(branch
), ".mergeoptions")) {
544 free(branch_mergeoptions
);
545 branch_mergeoptions
= xstrdup(v
);
549 if (!strcmp(k
, "merge.diffstat") || !strcmp(k
, "merge.stat"))
550 show_diffstat
= git_config_bool(k
, v
);
551 else if (!strcmp(k
, "pull.twohead"))
552 return git_config_string(&pull_twohead
, k
, v
);
553 else if (!strcmp(k
, "pull.octopus"))
554 return git_config_string(&pull_octopus
, k
, v
);
555 else if (!strcmp(k
, "merge.renormalize"))
556 option_renormalize
= git_config_bool(k
, v
);
557 else if (!strcmp(k
, "merge.log") || !strcmp(k
, "merge.summary")) {
559 shortlog_len
= git_config_bool_or_int(k
, v
, &is_bool
);
560 if (!is_bool
&& shortlog_len
< 0)
561 return error(_("%s: negative length %s"), k
, v
);
562 if (is_bool
&& shortlog_len
)
563 shortlog_len
= DEFAULT_MERGE_LOG_LEN
;
565 } else if (!strcmp(k
, "merge.ff")) {
566 int boolval
= git_config_maybe_bool(k
, v
);
568 allow_fast_forward
= boolval
;
569 } else if (v
&& !strcmp(v
, "only")) {
570 allow_fast_forward
= 1;
571 fast_forward_only
= 1;
572 } /* do not barf on values from future versions of git */
574 } else if (!strcmp(k
, "merge.defaulttoupstream")) {
575 default_to_upstream
= git_config_bool(k
, v
);
578 return git_diff_ui_config(k
, v
, cb
);
581 static int read_tree_trivial(unsigned char *common
, unsigned char *head
,
585 struct tree
*trees
[MAX_UNPACK_TREES
];
586 struct tree_desc t
[MAX_UNPACK_TREES
];
587 struct unpack_trees_options opts
;
589 memset(&opts
, 0, sizeof(opts
));
591 opts
.src_index
= &the_index
;
592 opts
.dst_index
= &the_index
;
594 opts
.verbose_update
= 1;
595 opts
.trivial_merges_only
= 1;
597 trees
[nr_trees
] = parse_tree_indirect(common
);
598 if (!trees
[nr_trees
++])
600 trees
[nr_trees
] = parse_tree_indirect(head
);
601 if (!trees
[nr_trees
++])
603 trees
[nr_trees
] = parse_tree_indirect(one
);
604 if (!trees
[nr_trees
++])
606 opts
.fn
= threeway_merge
;
607 cache_tree_free(&active_cache_tree
);
608 for (i
= 0; i
< nr_trees
; i
++) {
609 parse_tree(trees
[i
]);
610 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
612 if (unpack_trees(nr_trees
, t
, &opts
))
617 static void write_tree_trivial(unsigned char *sha1
)
619 if (write_cache_as_tree(sha1
, 0, NULL
))
620 die(_("git write-tree failed to write a tree"));
623 static const char *merge_argument(struct commit
*commit
)
626 return sha1_to_hex(commit
->object
.sha1
);
628 return EMPTY_TREE_SHA1_HEX
;
631 int try_merge_command(const char *strategy
, size_t xopts_nr
,
632 const char **xopts
, struct commit_list
*common
,
633 const char *head_arg
, struct commit_list
*remotes
)
636 int i
= 0, x
= 0, ret
;
637 struct commit_list
*j
;
638 struct strbuf buf
= STRBUF_INIT
;
640 args
= xmalloc((4 + xopts_nr
+ commit_list_count(common
) +
641 commit_list_count(remotes
)) * sizeof(char *));
642 strbuf_addf(&buf
, "merge-%s", strategy
);
644 for (x
= 0; x
< xopts_nr
; x
++) {
645 char *s
= xmalloc(strlen(xopts
[x
])+2+1);
647 strcpy(s
+2, xopts
[x
]);
650 for (j
= common
; j
; j
= j
->next
)
651 args
[i
++] = xstrdup(merge_argument(j
->item
));
653 args
[i
++] = head_arg
;
654 for (j
= remotes
; j
; j
= j
->next
)
655 args
[i
++] = xstrdup(merge_argument(j
->item
));
657 ret
= run_command_v_opt(args
, RUN_GIT_CMD
);
658 strbuf_release(&buf
);
660 for (x
= 0; x
< xopts_nr
; x
++)
661 free((void *)args
[i
++]);
662 for (j
= common
; j
; j
= j
->next
)
663 free((void *)args
[i
++]);
665 for (j
= remotes
; j
; j
= j
->next
)
666 free((void *)args
[i
++]);
669 if (read_cache() < 0)
670 die(_("failed to read the cache"));
671 resolve_undo_clear();
676 static int try_merge_strategy(const char *strategy
, struct commit_list
*common
,
677 struct commit
*head
, const char *head_arg
)
680 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
682 index_fd
= hold_locked_index(lock
, 1);
683 refresh_cache(REFRESH_QUIET
);
684 if (active_cache_changed
&&
685 (write_cache(index_fd
, active_cache
, active_nr
) ||
686 commit_locked_index(lock
)))
687 return error(_("Unable to write index."));
688 rollback_lock_file(lock
);
690 if (!strcmp(strategy
, "recursive") || !strcmp(strategy
, "subtree")) {
692 struct commit
*result
;
693 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
695 struct commit_list
*reversed
= NULL
;
696 struct merge_options o
;
697 struct commit_list
*j
;
699 if (remoteheads
->next
) {
700 error(_("Not handling anything other than two heads merge."));
704 init_merge_options(&o
);
705 if (!strcmp(strategy
, "subtree"))
706 o
.subtree_shift
= "";
708 o
.renormalize
= option_renormalize
;
709 o
.show_rename_progress
=
710 show_progress
== -1 ? isatty(2) : show_progress
;
712 for (x
= 0; x
< xopts_nr
; x
++)
713 if (parse_merge_opt(&o
, xopts
[x
]))
714 die(_("Unknown option for merge-recursive: -X%s"), xopts
[x
]);
716 o
.branch1
= head_arg
;
717 o
.branch2
= remoteheads
->item
->util
;
719 for (j
= common
; j
; j
= j
->next
)
720 commit_list_insert(j
->item
, &reversed
);
722 index_fd
= hold_locked_index(lock
, 1);
723 clean
= merge_recursive(&o
, head
,
724 remoteheads
->item
, reversed
, &result
);
725 if (active_cache_changed
&&
726 (write_cache(index_fd
, active_cache
, active_nr
) ||
727 commit_locked_index(lock
)))
728 die (_("unable to write %s"), get_index_file());
729 rollback_lock_file(lock
);
730 return clean
? 0 : 1;
732 return try_merge_command(strategy
, xopts_nr
, xopts
,
733 common
, head_arg
, remoteheads
);
737 static void count_diff_files(struct diff_queue_struct
*q
,
738 struct diff_options
*opt
, void *data
)
745 static int count_unmerged_entries(void)
749 for (i
= 0; i
< active_nr
; i
++)
750 if (ce_stage(active_cache
[i
]))
756 int checkout_fast_forward(const unsigned char *head
, const unsigned char *remote
)
758 struct tree
*trees
[MAX_UNPACK_TREES
];
759 struct unpack_trees_options opts
;
760 struct tree_desc t
[MAX_UNPACK_TREES
];
761 int i
, fd
, nr_trees
= 0;
762 struct dir_struct dir
;
763 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
765 refresh_cache(REFRESH_QUIET
);
767 fd
= hold_locked_index(lock_file
, 1);
769 memset(&trees
, 0, sizeof(trees
));
770 memset(&opts
, 0, sizeof(opts
));
771 memset(&t
, 0, sizeof(t
));
772 memset(&dir
, 0, sizeof(dir
));
773 dir
.flags
|= DIR_SHOW_IGNORED
;
774 dir
.exclude_per_dir
= ".gitignore";
778 opts
.src_index
= &the_index
;
779 opts
.dst_index
= &the_index
;
781 opts
.verbose_update
= 1;
783 opts
.fn
= twoway_merge
;
784 setup_unpack_trees_porcelain(&opts
, "merge");
786 trees
[nr_trees
] = parse_tree_indirect(head
);
787 if (!trees
[nr_trees
++])
789 trees
[nr_trees
] = parse_tree_indirect(remote
);
790 if (!trees
[nr_trees
++])
792 for (i
= 0; i
< nr_trees
; i
++) {
793 parse_tree(trees
[i
]);
794 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
796 if (unpack_trees(nr_trees
, t
, &opts
))
798 if (write_cache(fd
, active_cache
, active_nr
) ||
799 commit_locked_index(lock_file
))
800 die(_("unable to write new index file"));
804 static void split_merge_strategies(const char *string
, struct strategy
**list
,
812 buf
= xstrdup(string
);
817 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
818 (*list
)[(*nr
)++].name
= xstrdup(q
);
823 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
824 (*list
)[(*nr
)++].name
= xstrdup(q
);
830 static void add_strategies(const char *string
, unsigned attr
)
832 struct strategy
*list
= NULL
;
833 int list_alloc
= 0, list_nr
= 0, i
;
835 memset(&list
, 0, sizeof(list
));
836 split_merge_strategies(string
, &list
, &list_nr
, &list_alloc
);
838 for (i
= 0; i
< list_nr
; i
++)
839 append_strategy(get_strategy(list
[i
].name
));
842 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
843 if (all_strategy
[i
].attr
& attr
)
844 append_strategy(&all_strategy
[i
]);
848 static void write_merge_msg(struct strbuf
*msg
)
850 int fd
= open(git_path("MERGE_MSG"), O_WRONLY
| O_CREAT
, 0666);
852 die_errno(_("Could not open '%s' for writing"),
853 git_path("MERGE_MSG"));
854 if (write_in_full(fd
, msg
->buf
, msg
->len
) != msg
->len
)
855 die_errno(_("Could not write to '%s'"), git_path("MERGE_MSG"));
859 static void read_merge_msg(struct strbuf
*msg
)
862 if (strbuf_read_file(msg
, git_path("MERGE_MSG"), 0) < 0)
863 die_errno(_("Could not read from '%s'"), git_path("MERGE_MSG"));
866 static void write_merge_state(void);
867 static void abort_commit(const char *err_msg
)
870 error("%s", err_msg
);
872 _("Not committing merge; use 'git commit' to complete the merge.\n"));
877 static void prepare_to_commit(void)
879 struct strbuf msg
= STRBUF_INIT
;
880 strbuf_addbuf(&msg
, &merge_msg
);
881 strbuf_addch(&msg
, '\n');
882 write_merge_msg(&msg
);
883 run_hook(get_index_file(), "prepare-commit-msg",
884 git_path("MERGE_MSG"), "merge", NULL
, NULL
);
886 if (launch_editor(git_path("MERGE_MSG"), NULL
, NULL
))
889 read_merge_msg(&msg
);
890 stripspace(&msg
, option_edit
);
892 abort_commit(_("Empty commit message."));
893 strbuf_release(&merge_msg
);
894 strbuf_addbuf(&merge_msg
, &msg
);
895 strbuf_release(&msg
);
898 static int merge_trivial(struct commit
*head
)
900 unsigned char result_tree
[20], result_commit
[20];
901 struct commit_list
*parent
= xmalloc(sizeof(*parent
));
903 write_tree_trivial(result_tree
);
904 printf(_("Wonderful.\n"));
906 parent
->next
= xmalloc(sizeof(*parent
->next
));
907 parent
->next
->item
= remoteheads
->item
;
908 parent
->next
->next
= NULL
;
910 commit_tree(merge_msg
.buf
, result_tree
, parent
, result_commit
, NULL
);
911 finish(head
, result_commit
, "In-index merge");
916 static int finish_automerge(struct commit
*head
,
917 struct commit_list
*common
,
918 unsigned char *result_tree
,
919 const char *wt_strategy
)
921 struct commit_list
*parents
= NULL
, *j
;
922 struct strbuf buf
= STRBUF_INIT
;
923 unsigned char result_commit
[20];
925 free_commit_list(common
);
926 if (allow_fast_forward
) {
927 parents
= remoteheads
;
928 commit_list_insert(head
, &parents
);
929 parents
= reduce_heads(parents
);
931 struct commit_list
**pptr
= &parents
;
933 pptr
= &commit_list_insert(head
,
935 for (j
= remoteheads
; j
; j
= j
->next
)
936 pptr
= &commit_list_insert(j
->item
, pptr
)->next
;
938 strbuf_addch(&merge_msg
, '\n');
940 free_commit_list(remoteheads
);
941 commit_tree(merge_msg
.buf
, result_tree
, parents
, result_commit
, NULL
);
942 strbuf_addf(&buf
, "Merge made by the '%s' strategy.", wt_strategy
);
943 finish(head
, result_commit
, buf
.buf
);
944 strbuf_release(&buf
);
949 static int suggest_conflicts(int renormalizing
)
954 fp
= fopen(git_path("MERGE_MSG"), "a");
956 die_errno(_("Could not open '%s' for writing"),
957 git_path("MERGE_MSG"));
958 fprintf(fp
, "\nConflicts:\n");
959 for (pos
= 0; pos
< active_nr
; pos
++) {
960 struct cache_entry
*ce
= active_cache
[pos
];
963 fprintf(fp
, "\t%s\n", ce
->name
);
964 while (pos
+ 1 < active_nr
&&
966 active_cache
[pos
+ 1]->name
))
971 rerere(allow_rerere_auto
);
972 printf(_("Automatic merge failed; "
973 "fix conflicts and then commit the result.\n"));
977 static struct commit
*is_old_style_invocation(int argc
, const char **argv
,
978 const unsigned char *head
)
980 struct commit
*second_token
= NULL
;
982 unsigned char second_sha1
[20];
984 if (get_sha1(argv
[1], second_sha1
))
986 second_token
= lookup_commit_reference_gently(second_sha1
, 0);
988 die(_("'%s' is not a commit"), argv
[1]);
989 if (hashcmp(second_token
->object
.sha1
, head
))
995 static int evaluate_result(void)
1000 /* Check how many files differ. */
1001 init_revisions(&rev
, "");
1002 setup_revisions(0, NULL
, &rev
, NULL
);
1003 rev
.diffopt
.output_format
|=
1004 DIFF_FORMAT_CALLBACK
;
1005 rev
.diffopt
.format_callback
= count_diff_files
;
1006 rev
.diffopt
.format_callback_data
= &cnt
;
1007 run_diff_files(&rev
, 0);
1010 * Check how many unmerged entries are
1013 cnt
+= count_unmerged_entries();
1019 * Pretend as if the user told us to merge with the tracking
1020 * branch we have for the upstream of the current branch
1022 static int setup_with_upstream(const char ***argv
)
1024 struct branch
*branch
= branch_get(NULL
);
1029 die(_("No current branch."));
1030 if (!branch
->remote
)
1031 die(_("No remote for the current branch."));
1032 if (!branch
->merge_nr
)
1033 die(_("No default upstream defined for the current branch."));
1035 args
= xcalloc(branch
->merge_nr
+ 1, sizeof(char *));
1036 for (i
= 0; i
< branch
->merge_nr
; i
++) {
1037 if (!branch
->merge
[i
]->dst
)
1038 die(_("No remote tracking branch for %s from %s"),
1039 branch
->merge
[i
]->src
, branch
->remote_name
);
1040 args
[i
] = branch
->merge
[i
]->dst
;
1047 static void write_merge_state(void)
1050 struct commit_list
*j
;
1051 struct strbuf buf
= STRBUF_INIT
;
1053 for (j
= remoteheads
; j
; j
= j
->next
)
1054 strbuf_addf(&buf
, "%s\n",
1055 sha1_to_hex(j
->item
->object
.sha1
));
1056 fd
= open(git_path("MERGE_HEAD"), O_WRONLY
| O_CREAT
, 0666);
1058 die_errno(_("Could not open '%s' for writing"),
1059 git_path("MERGE_HEAD"));
1060 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1061 die_errno(_("Could not write to '%s'"), git_path("MERGE_HEAD"));
1063 strbuf_addch(&merge_msg
, '\n');
1064 write_merge_msg(&merge_msg
);
1065 fd
= open(git_path("MERGE_MODE"), O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
1067 die_errno(_("Could not open '%s' for writing"),
1068 git_path("MERGE_MODE"));
1070 if (!allow_fast_forward
)
1071 strbuf_addf(&buf
, "no-ff");
1072 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1073 die_errno(_("Could not write to '%s'"), git_path("MERGE_MODE"));
1077 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
1079 unsigned char result_tree
[20];
1080 unsigned char stash
[20];
1081 unsigned char head_sha1
[20];
1082 struct commit
*head_commit
;
1083 struct strbuf buf
= STRBUF_INIT
;
1084 const char *head_arg
;
1086 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
1087 struct commit_list
*common
= NULL
;
1088 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
1089 struct commit_list
**remotes
= &remoteheads
;
1091 if (argc
== 2 && !strcmp(argv
[1], "-h"))
1092 usage_with_options(builtin_merge_usage
, builtin_merge_options
);
1095 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1098 branch
= resolve_ref("HEAD", head_sha1
, 0, &flag
);
1099 if (branch
&& !prefixcmp(branch
, "refs/heads/"))
1101 if (!branch
|| is_null_sha1(head_sha1
))
1104 head_commit
= lookup_commit_or_die(head_sha1
, "HEAD");
1106 git_config(git_merge_config
, NULL
);
1108 if (branch_mergeoptions
)
1109 parse_branch_merge_options(branch_mergeoptions
);
1110 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
1111 builtin_merge_usage
, 0);
1113 if (verbosity
< 0 && show_progress
== -1)
1116 if (abort_current_merge
) {
1118 const char *nargv
[] = {"reset", "--merge", NULL
};
1120 if (!file_exists(git_path("MERGE_HEAD")))
1121 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1123 /* Invoke 'git reset --merge' */
1124 return cmd_reset(nargc
, nargv
, prefix
);
1127 if (read_cache_unmerged())
1128 die_resolve_conflict("merge");
1130 if (file_exists(git_path("MERGE_HEAD"))) {
1132 * There is no unmerged entry, don't advise 'git
1133 * add/rm <file>', just 'git commit'.
1135 if (advice_resolve_conflict
)
1136 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1137 "Please, commit your changes before you can merge."));
1139 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1141 if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
1142 if (advice_resolve_conflict
)
1143 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1144 "Please, commit your changes before you can merge."));
1146 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1148 resolve_undo_clear();
1154 if (!allow_fast_forward
)
1155 die(_("You cannot combine --squash with --no-ff."));
1159 if (!allow_fast_forward
&& fast_forward_only
)
1160 die(_("You cannot combine --no-ff with --ff-only."));
1162 if (!abort_current_merge
) {
1163 if (!argc
&& default_to_upstream
)
1164 argc
= setup_with_upstream(&argv
);
1165 else if (argc
== 1 && !strcmp(argv
[0], "-"))
1169 usage_with_options(builtin_merge_usage
,
1170 builtin_merge_options
);
1173 * This could be traditional "merge <msg> HEAD <commit>..." and
1174 * the way we can tell it is to see if the second token is HEAD,
1175 * but some people might have misused the interface and used a
1176 * committish that is the same as HEAD there instead.
1177 * Traditional format never would have "-m" so it is an
1178 * additional safety measure to check for it.
1181 if (!have_message
&& head_commit
&&
1182 is_old_style_invocation(argc
, argv
, head_commit
->object
.sha1
)) {
1183 strbuf_addstr(&merge_msg
, argv
[0]);
1187 } else if (!head_commit
) {
1188 struct object
*remote_head
;
1190 * If the merged head is a valid one there is no reason
1191 * to forbid "git merge" into a branch yet to be born.
1192 * We do the same for "git pull".
1195 die(_("Can merge only exactly one commit into "
1198 die(_("Squash commit into empty head not supported yet"));
1199 if (!allow_fast_forward
)
1200 die(_("Non-fast-forward commit does not make sense into "
1202 remote_head
= want_commit(argv
[0]);
1204 die(_("%s - not something we can merge"), argv
[0]);
1205 read_empty(remote_head
->sha1
, 0);
1206 update_ref("initial pull", "HEAD", remote_head
->sha1
, NULL
, 0,
1210 struct strbuf merge_names
= STRBUF_INIT
;
1212 /* We are invoked directly as the first-class UI. */
1216 * All the rest are the commits being merged;
1217 * prepare the standard merge summary message to
1218 * be appended to the given message. If remote
1219 * is invalid we will die later in the common
1220 * codepath so we discard the error in this
1223 for (i
= 0; i
< argc
; i
++)
1224 merge_name(argv
[i
], &merge_names
);
1226 if (!have_message
|| shortlog_len
) {
1227 fmt_merge_msg(&merge_names
, &merge_msg
, !have_message
,
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 strbuf_addstr(&buf
, "merge");
1239 for (i
= 0; i
< argc
; i
++)
1240 strbuf_addf(&buf
, " %s", argv
[i
]);
1241 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
1244 for (i
= 0; i
< argc
; i
++) {
1246 struct commit
*commit
;
1248 o
= want_commit(argv
[i
]);
1250 die(_("%s - not something we can merge"), argv
[i
]);
1251 commit
= lookup_commit(o
->sha1
);
1252 commit
->util
= (void *)argv
[i
];
1253 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1255 strbuf_addf(&buf
, "GITHEAD_%s", sha1_to_hex(o
->sha1
));
1256 setenv(buf
.buf
, argv
[i
], 1);
1260 if (!use_strategies
) {
1261 if (!remoteheads
->next
)
1262 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
1264 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
1267 for (i
= 0; i
< use_strategies_nr
; i
++) {
1268 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
1269 allow_fast_forward
= 0;
1270 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
1274 if (!remoteheads
->next
)
1275 common
= get_merge_bases(head_commit
, remoteheads
->item
, 1);
1277 struct commit_list
*list
= remoteheads
;
1278 commit_list_insert(head_commit
, &list
);
1279 common
= get_octopus_merge_bases(list
);
1283 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head_commit
->object
.sha1
,
1284 NULL
, 0, DIE_ON_ERR
);
1287 ; /* No common ancestors found. We need a real merge. */
1288 else if (!remoteheads
->next
&& !common
->next
&&
1289 common
->item
== remoteheads
->item
) {
1291 * If head can reach all the merge then we are up to date.
1292 * but first the most common case of merging one remote.
1294 finish_up_to_date("Already up-to-date.");
1296 } else if (allow_fast_forward
&& !remoteheads
->next
&&
1298 !hashcmp(common
->item
->object
.sha1
, head_commit
->object
.sha1
)) {
1299 /* Again the most common case of merging one remote. */
1300 struct strbuf msg
= STRBUF_INIT
;
1304 strcpy(hex
, find_unique_abbrev(head_commit
->object
.sha1
, DEFAULT_ABBREV
));
1307 printf(_("Updating %s..%s\n"),
1309 find_unique_abbrev(remoteheads
->item
->object
.sha1
,
1311 strbuf_addstr(&msg
, "Fast-forward");
1314 " (no commit created; -m option ignored)");
1315 o
= want_commit(sha1_to_hex(remoteheads
->item
->object
.sha1
));
1319 if (checkout_fast_forward(head_commit
->object
.sha1
, remoteheads
->item
->object
.sha1
))
1322 finish(head_commit
, o
->sha1
, msg
.buf
);
1325 } else if (!remoteheads
->next
&& common
->next
)
1328 * We are not doing octopus and not fast-forward. Need
1331 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1333 * We are not doing octopus, not fast-forward, and have
1336 refresh_cache(REFRESH_QUIET
);
1337 if (allow_trivial
&& !fast_forward_only
) {
1338 /* See if it is really trivial. */
1339 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1340 printf(_("Trying really trivial in-index merge...\n"));
1341 if (!read_tree_trivial(common
->item
->object
.sha1
,
1342 head_commit
->object
.sha1
, remoteheads
->item
->object
.sha1
))
1343 return merge_trivial(head_commit
);
1344 printf(_("Nope.\n"));
1348 * An octopus. If we can reach all the remote we are up
1352 struct commit_list
*j
;
1354 for (j
= remoteheads
; j
; j
= j
->next
) {
1355 struct commit_list
*common_one
;
1358 * Here we *have* to calculate the individual
1359 * merge_bases again, otherwise "git merge HEAD^
1360 * HEAD^^" would be missed.
1362 common_one
= get_merge_bases(head_commit
, j
->item
, 1);
1363 if (hashcmp(common_one
->item
->object
.sha1
,
1364 j
->item
->object
.sha1
)) {
1370 finish_up_to_date("Already up-to-date. Yeeah!");
1375 if (fast_forward_only
)
1376 die(_("Not possible to fast-forward, aborting."));
1378 /* We are going to make a new commit. */
1379 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1382 * At this point, we need a real merge. No matter what strategy
1383 * we use, it would operate on the index, possibly affecting the
1384 * working tree, and when resolved cleanly, have the desired
1385 * tree in the index -- this means that the index must be in
1386 * sync with the head commit. The strategies are responsible
1389 if (use_strategies_nr
== 1 ||
1391 * Stash away the local changes so that we can try more than one.
1394 hashcpy(stash
, null_sha1
);
1396 for (i
= 0; i
< use_strategies_nr
; i
++) {
1399 printf(_("Rewinding the tree to pristine...\n"));
1400 restore_state(head_commit
->object
.sha1
, stash
);
1402 if (use_strategies_nr
!= 1)
1403 printf(_("Trying merge strategy %s...\n"),
1404 use_strategies
[i
]->name
);
1406 * Remember which strategy left the state in the working
1409 wt_strategy
= use_strategies
[i
]->name
;
1411 ret
= try_merge_strategy(use_strategies
[i
]->name
,
1412 common
, head_commit
, head_arg
);
1413 if (!option_commit
&& !ret
) {
1416 * This is necessary here just to avoid writing
1417 * the tree, but later we will *not* exit with
1418 * status code 1 because merge_was_ok is set.
1425 * The backend exits with 1 when conflicts are
1426 * left to be resolved, with 2 when it does not
1427 * handle the given merge at all.
1430 int cnt
= evaluate_result();
1432 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1433 best_strategy
= use_strategies
[i
]->name
;
1443 /* Automerge succeeded. */
1444 write_tree_trivial(result_tree
);
1445 automerge_was_ok
= 1;
1450 * If we have a resulting tree, that means the strategy module
1451 * auto resolved the merge cleanly.
1453 if (automerge_was_ok
)
1454 return finish_automerge(head_commit
, common
, result_tree
,
1458 * Pick the result from the best strategy and have the user fix
1461 if (!best_strategy
) {
1462 restore_state(head_commit
->object
.sha1
, stash
);
1463 if (use_strategies_nr
> 1)
1465 _("No merge strategy handled the merge.\n"));
1467 fprintf(stderr
, _("Merge with strategy %s failed.\n"),
1468 use_strategies
[0]->name
);
1470 } else if (best_strategy
== wt_strategy
)
1471 ; /* We already have its result in the working tree. */
1473 printf(_("Rewinding the tree to pristine...\n"));
1474 restore_state(head_commit
->object
.sha1
, stash
);
1475 printf(_("Using the %s to prepare resolving by hand.\n"),
1477 try_merge_strategy(best_strategy
, common
, head_commit
, head_arg
);
1481 finish(head_commit
, NULL
, NULL
);
1483 write_merge_state();
1486 fprintf(stderr
, _("Automatic merge went well; "
1487 "stopped before committing as requested\n"));
1490 return suggest_conflicts(option_renormalize
);