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 "git merge [options] [<commit>...]",
44 "git merge [options] <msg> HEAD <commit>",
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
;
52 static int allow_trivial
= 1, have_message
;
53 static struct strbuf merge_msg
;
54 static struct commit_list
*remoteheads
;
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 "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 "show a diffstat at the end of the merge"),
187 OPT_BOOLEAN(0, "summary", &show_diffstat
, "(synonym to --stat)"),
188 { OPTION_INTEGER
, 0, "log", &shortlog_len
, "n",
189 "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 "create a single commit instead of doing a merge"),
193 OPT_BOOLEAN(0, "commit", &option_commit
,
194 "perform a commit if the merge succeeds (default)"),
195 OPT_BOOLEAN('e', "edit", &option_edit
,
196 "edit message before committing"),
197 OPT_BOOLEAN(0, "ff", &allow_fast_forward
,
198 "allow fast-forward (default)"),
199 OPT_BOOLEAN(0, "ff-only", &fast_forward_only
,
200 "abort if fast-forward is not possible"),
201 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto
),
202 OPT_CALLBACK('s', "strategy", &use_strategies
, "strategy",
203 "merge strategy to use", option_parse_strategy
),
204 OPT_CALLBACK('X', "strategy-option", &xopts
, "option=value",
205 "option for selected merge strategy", option_parse_x
),
206 OPT_CALLBACK('m', "message", &merge_msg
, "message",
207 "merge commit message (for a non-fast-forward merge)",
208 option_parse_message
),
209 OPT__VERBOSITY(&verbosity
),
210 OPT_BOOLEAN(0, "abort", &abort_current_merge
,
211 "abort the current in-progress merge"),
212 OPT_SET_INT(0, "progress", &show_progress
, "force progress reporting", 1),
213 { OPTION_STRING
, 'S', "gpg-sign", &sign_commit
, "key id",
214 "GPG sign commit", PARSE_OPT_OPTARG
, NULL
, (intptr_t) "" },
218 /* Cleans up metadata that is uninteresting after a succeeded merge. */
219 static void drop_save(void)
221 unlink(git_path("MERGE_HEAD"));
222 unlink(git_path("MERGE_MSG"));
223 unlink(git_path("MERGE_MODE"));
226 static int save_state(unsigned char *stash
)
229 struct child_process cp
;
230 struct strbuf buffer
= STRBUF_INIT
;
231 const char *argv
[] = {"stash", "create", NULL
};
233 memset(&cp
, 0, sizeof(cp
));
238 if (start_command(&cp
))
239 die(_("could not run stash."));
240 len
= strbuf_read(&buffer
, cp
.out
, 1024);
243 if (finish_command(&cp
) || len
< 0)
244 die(_("stash failed"));
245 else if (!len
) /* no changes */
247 strbuf_setlen(&buffer
, buffer
.len
-1);
248 if (get_sha1(buffer
.buf
, stash
))
249 die(_("not a valid object: %s"), buffer
.buf
);
253 static void read_empty(unsigned const char *sha1
, int verbose
)
258 args
[i
++] = "read-tree";
263 args
[i
++] = EMPTY_TREE_SHA1_HEX
;
264 args
[i
++] = sha1_to_hex(sha1
);
267 if (run_command_v_opt(args
, RUN_GIT_CMD
))
268 die(_("read-tree failed"));
271 static void reset_hard(unsigned const char *sha1
, int verbose
)
276 args
[i
++] = "read-tree";
279 args
[i
++] = "--reset";
281 args
[i
++] = sha1_to_hex(sha1
);
284 if (run_command_v_opt(args
, RUN_GIT_CMD
))
285 die(_("read-tree failed"));
288 static void restore_state(const unsigned char *head
,
289 const unsigned char *stash
)
291 struct strbuf sb
= STRBUF_INIT
;
292 const char *args
[] = { "stash", "apply", NULL
, NULL
};
294 if (is_null_sha1(stash
))
299 args
[2] = sha1_to_hex(stash
);
302 * It is OK to ignore error here, for example when there was
303 * nothing to restore.
305 run_command_v_opt(args
, RUN_GIT_CMD
);
308 refresh_cache(REFRESH_QUIET
);
311 /* This is called when no merge was necessary. */
312 static void finish_up_to_date(const char *msg
)
315 printf("%s%s\n", squash
? _(" (nothing to squash)") : "", msg
);
319 static void squash_message(struct commit
*commit
)
322 struct strbuf out
= STRBUF_INIT
;
323 struct commit_list
*j
;
325 struct pretty_print_context ctx
= {0};
327 printf(_("Squash commit -- not updating HEAD\n"));
328 fd
= open(git_path("SQUASH_MSG"), O_WRONLY
| O_CREAT
, 0666);
330 die_errno(_("Could not write to '%s'"), git_path("SQUASH_MSG"));
332 init_revisions(&rev
, NULL
);
333 rev
.ignore_merges
= 1;
334 rev
.commit_format
= CMIT_FMT_MEDIUM
;
336 commit
->object
.flags
|= UNINTERESTING
;
337 add_pending_object(&rev
, &commit
->object
, NULL
);
339 for (j
= remoteheads
; j
; j
= j
->next
)
340 add_pending_object(&rev
, &j
->item
->object
, NULL
);
342 setup_revisions(0, NULL
, &rev
, NULL
);
343 if (prepare_revision_walk(&rev
))
344 die(_("revision walk setup failed"));
346 ctx
.abbrev
= rev
.abbrev
;
347 ctx
.date_mode
= rev
.date_mode
;
348 ctx
.fmt
= rev
.commit_format
;
350 strbuf_addstr(&out
, "Squashed commit of the following:\n");
351 while ((commit
= get_revision(&rev
)) != NULL
) {
352 strbuf_addch(&out
, '\n');
353 strbuf_addf(&out
, "commit %s\n",
354 sha1_to_hex(commit
->object
.sha1
));
355 pretty_print_commit(&ctx
, commit
, &out
);
357 if (write(fd
, out
.buf
, out
.len
) < 0)
358 die_errno(_("Writing SQUASH_MSG"));
360 die_errno(_("Finishing SQUASH_MSG"));
361 strbuf_release(&out
);
364 static void finish(struct commit
*head_commit
,
365 const unsigned char *new_head
, const char *msg
)
367 struct strbuf reflog_message
= STRBUF_INIT
;
368 const unsigned char *head
= head_commit
->object
.sha1
;
371 strbuf_addstr(&reflog_message
, getenv("GIT_REFLOG_ACTION"));
375 strbuf_addf(&reflog_message
, "%s: %s",
376 getenv("GIT_REFLOG_ACTION"), msg
);
379 squash_message(head_commit
);
381 if (verbosity
>= 0 && !merge_msg
.len
)
382 printf(_("No merge message -- not updating HEAD\n"));
384 const char *argv_gc_auto
[] = { "gc", "--auto", NULL
};
385 update_ref(reflog_message
.buf
, "HEAD",
389 * We ignore errors in 'gc --auto', since the
390 * user should see them.
392 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
395 if (new_head
&& show_diffstat
) {
396 struct diff_options opts
;
398 opts
.output_format
|=
399 DIFF_FORMAT_SUMMARY
| DIFF_FORMAT_DIFFSTAT
;
400 opts
.detect_rename
= DIFF_DETECT_RENAME
;
401 if (diff_setup_done(&opts
) < 0)
402 die(_("diff_setup_done failed"));
403 diff_tree_sha1(head
, new_head
, "", &opts
);
408 /* Run a post-merge hook */
409 run_hook(NULL
, "post-merge", squash
? "1" : "0", NULL
);
411 strbuf_release(&reflog_message
);
414 static struct object
*want_commit(const char *name
)
417 unsigned char sha1
[20];
418 if (get_sha1(name
, sha1
))
420 obj
= parse_object(sha1
);
421 return peel_to_type(name
, 0, obj
, OBJ_COMMIT
);
424 /* Get the name for the merge commit's message. */
425 static void merge_name(const char *remote
, struct strbuf
*msg
)
427 struct object
*remote_head
;
428 unsigned char branch_head
[20], buf_sha
[20];
429 struct strbuf buf
= STRBUF_INIT
;
430 struct strbuf bname
= STRBUF_INIT
;
435 strbuf_branchname(&bname
, remote
);
438 memset(branch_head
, 0, sizeof(branch_head
));
439 remote_head
= want_commit(remote
);
441 die(_("'%s' does not point to a commit"), remote
);
443 if (dwim_ref(remote
, strlen(remote
), branch_head
, &found_ref
) > 0) {
444 if (!prefixcmp(found_ref
, "refs/heads/")) {
445 strbuf_addf(msg
, "%s\t\tbranch '%s' of .\n",
446 sha1_to_hex(branch_head
), remote
);
449 if (!prefixcmp(found_ref
, "refs/remotes/")) {
450 strbuf_addf(msg
, "%s\t\tremote-tracking branch '%s' of .\n",
451 sha1_to_hex(branch_head
), remote
);
456 /* See if remote matches <name>^^^.. or <name>~<number> */
457 for (len
= 0, ptr
= remote
+ strlen(remote
);
458 remote
< ptr
&& ptr
[-1] == '^';
465 ptr
= strrchr(remote
, '~');
467 int seen_nonzero
= 0;
470 while (*++ptr
&& isdigit(*ptr
)) {
471 seen_nonzero
|= (*ptr
!= '0');
475 len
= 0; /* not ...~<number> */
476 else if (seen_nonzero
)
479 early
= 1; /* "name~" is "name~1"! */
483 struct strbuf truname
= STRBUF_INIT
;
484 strbuf_addstr(&truname
, "refs/heads/");
485 strbuf_addstr(&truname
, remote
);
486 strbuf_setlen(&truname
, truname
.len
- len
);
487 if (resolve_ref(truname
.buf
, buf_sha
, 1, NULL
)) {
489 "%s\t\tbranch '%s'%s of .\n",
490 sha1_to_hex(remote_head
->sha1
),
492 (early
? " (early part)" : ""));
493 strbuf_release(&truname
);
498 if (!strcmp(remote
, "FETCH_HEAD") &&
499 !access(git_path("FETCH_HEAD"), R_OK
)) {
501 struct strbuf line
= STRBUF_INIT
;
504 fp
= fopen(git_path("FETCH_HEAD"), "r");
506 die_errno(_("could not open '%s' for reading"),
507 git_path("FETCH_HEAD"));
508 strbuf_getline(&line
, fp
, '\n');
510 ptr
= strstr(line
.buf
, "\tnot-for-merge\t");
512 strbuf_remove(&line
, ptr
-line
.buf
+1, 13);
513 strbuf_addbuf(msg
, &line
);
514 strbuf_release(&line
);
517 strbuf_addf(msg
, "%s\t\tcommit '%s'\n",
518 sha1_to_hex(remote_head
->sha1
), remote
);
520 strbuf_release(&buf
);
521 strbuf_release(&bname
);
524 static void parse_branch_merge_options(char *bmo
)
531 argc
= split_cmdline(bmo
, &argv
);
533 die(_("Bad branch.%s.mergeoptions string: %s"), branch
,
534 split_cmdline_strerror(argc
));
535 argv
= xrealloc(argv
, sizeof(*argv
) * (argc
+ 2));
536 memmove(argv
+ 1, argv
, sizeof(*argv
) * (argc
+ 1));
538 argv
[0] = "branch.*.mergeoptions";
539 parse_options(argc
, argv
, NULL
, builtin_merge_options
,
540 builtin_merge_usage
, 0);
544 static int git_merge_config(const char *k
, const char *v
, void *cb
)
548 if (branch
&& !prefixcmp(k
, "branch.") &&
549 !prefixcmp(k
+ 7, branch
) &&
550 !strcmp(k
+ 7 + strlen(branch
), ".mergeoptions")) {
551 free(branch_mergeoptions
);
552 branch_mergeoptions
= xstrdup(v
);
556 if (!strcmp(k
, "merge.diffstat") || !strcmp(k
, "merge.stat"))
557 show_diffstat
= git_config_bool(k
, v
);
558 else if (!strcmp(k
, "pull.twohead"))
559 return git_config_string(&pull_twohead
, k
, v
);
560 else if (!strcmp(k
, "pull.octopus"))
561 return git_config_string(&pull_octopus
, k
, v
);
562 else if (!strcmp(k
, "merge.renormalize"))
563 option_renormalize
= git_config_bool(k
, v
);
564 else if (!strcmp(k
, "merge.ff")) {
565 int boolval
= git_config_maybe_bool(k
, v
);
567 allow_fast_forward
= boolval
;
568 } else if (v
&& !strcmp(v
, "only")) {
569 allow_fast_forward
= 1;
570 fast_forward_only
= 1;
571 } /* do not barf on values from future versions of git */
573 } else if (!strcmp(k
, "merge.defaulttoupstream")) {
574 default_to_upstream
= git_config_bool(k
, v
);
578 status
= fmt_merge_msg_config(k
, v
, cb
);
581 status
= git_gpg_config(k
, v
, NULL
);
584 return git_diff_ui_config(k
, v
, cb
);
587 static int read_tree_trivial(unsigned char *common
, unsigned char *head
,
591 struct tree
*trees
[MAX_UNPACK_TREES
];
592 struct tree_desc t
[MAX_UNPACK_TREES
];
593 struct unpack_trees_options opts
;
595 memset(&opts
, 0, sizeof(opts
));
597 opts
.src_index
= &the_index
;
598 opts
.dst_index
= &the_index
;
600 opts
.verbose_update
= 1;
601 opts
.trivial_merges_only
= 1;
603 trees
[nr_trees
] = parse_tree_indirect(common
);
604 if (!trees
[nr_trees
++])
606 trees
[nr_trees
] = parse_tree_indirect(head
);
607 if (!trees
[nr_trees
++])
609 trees
[nr_trees
] = parse_tree_indirect(one
);
610 if (!trees
[nr_trees
++])
612 opts
.fn
= threeway_merge
;
613 cache_tree_free(&active_cache_tree
);
614 for (i
= 0; i
< nr_trees
; i
++) {
615 parse_tree(trees
[i
]);
616 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
618 if (unpack_trees(nr_trees
, t
, &opts
))
623 static void write_tree_trivial(unsigned char *sha1
)
625 if (write_cache_as_tree(sha1
, 0, NULL
))
626 die(_("git write-tree failed to write a tree"));
629 static const char *merge_argument(struct commit
*commit
)
632 return sha1_to_hex(commit
->object
.sha1
);
634 return EMPTY_TREE_SHA1_HEX
;
637 int try_merge_command(const char *strategy
, size_t xopts_nr
,
638 const char **xopts
, struct commit_list
*common
,
639 const char *head_arg
, struct commit_list
*remotes
)
642 int i
= 0, x
= 0, ret
;
643 struct commit_list
*j
;
644 struct strbuf buf
= STRBUF_INIT
;
646 args
= xmalloc((4 + xopts_nr
+ commit_list_count(common
) +
647 commit_list_count(remotes
)) * sizeof(char *));
648 strbuf_addf(&buf
, "merge-%s", strategy
);
650 for (x
= 0; x
< xopts_nr
; x
++) {
651 char *s
= xmalloc(strlen(xopts
[x
])+2+1);
653 strcpy(s
+2, xopts
[x
]);
656 for (j
= common
; j
; j
= j
->next
)
657 args
[i
++] = xstrdup(merge_argument(j
->item
));
659 args
[i
++] = head_arg
;
660 for (j
= remotes
; j
; j
= j
->next
)
661 args
[i
++] = xstrdup(merge_argument(j
->item
));
663 ret
= run_command_v_opt(args
, RUN_GIT_CMD
);
664 strbuf_release(&buf
);
666 for (x
= 0; x
< xopts_nr
; x
++)
667 free((void *)args
[i
++]);
668 for (j
= common
; j
; j
= j
->next
)
669 free((void *)args
[i
++]);
671 for (j
= remotes
; j
; j
= j
->next
)
672 free((void *)args
[i
++]);
675 if (read_cache() < 0)
676 die(_("failed to read the cache"));
677 resolve_undo_clear();
682 static int try_merge_strategy(const char *strategy
, struct commit_list
*common
,
683 struct commit
*head
, const char *head_arg
)
686 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
688 index_fd
= hold_locked_index(lock
, 1);
689 refresh_cache(REFRESH_QUIET
);
690 if (active_cache_changed
&&
691 (write_cache(index_fd
, active_cache
, active_nr
) ||
692 commit_locked_index(lock
)))
693 return error(_("Unable to write index."));
694 rollback_lock_file(lock
);
696 if (!strcmp(strategy
, "recursive") || !strcmp(strategy
, "subtree")) {
698 struct commit
*result
;
699 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
701 struct commit_list
*reversed
= NULL
;
702 struct merge_options o
;
703 struct commit_list
*j
;
705 if (remoteheads
->next
) {
706 error(_("Not handling anything other than two heads merge."));
710 init_merge_options(&o
);
711 if (!strcmp(strategy
, "subtree"))
712 o
.subtree_shift
= "";
714 o
.renormalize
= option_renormalize
;
715 o
.show_rename_progress
=
716 show_progress
== -1 ? isatty(2) : show_progress
;
718 for (x
= 0; x
< xopts_nr
; x
++)
719 if (parse_merge_opt(&o
, xopts
[x
]))
720 die(_("Unknown option for merge-recursive: -X%s"), xopts
[x
]);
722 o
.branch1
= head_arg
;
723 o
.branch2
= remoteheads
->item
->util
;
725 for (j
= common
; j
; j
= j
->next
)
726 commit_list_insert(j
->item
, &reversed
);
728 index_fd
= hold_locked_index(lock
, 1);
729 clean
= merge_recursive(&o
, head
,
730 remoteheads
->item
, reversed
, &result
);
731 if (active_cache_changed
&&
732 (write_cache(index_fd
, active_cache
, active_nr
) ||
733 commit_locked_index(lock
)))
734 die (_("unable to write %s"), get_index_file());
735 rollback_lock_file(lock
);
736 return clean
? 0 : 1;
738 return try_merge_command(strategy
, xopts_nr
, xopts
,
739 common
, head_arg
, remoteheads
);
743 static void count_diff_files(struct diff_queue_struct
*q
,
744 struct diff_options
*opt
, void *data
)
751 static int count_unmerged_entries(void)
755 for (i
= 0; i
< active_nr
; i
++)
756 if (ce_stage(active_cache
[i
]))
762 int checkout_fast_forward(const unsigned char *head
, const unsigned char *remote
)
764 struct tree
*trees
[MAX_UNPACK_TREES
];
765 struct unpack_trees_options opts
;
766 struct tree_desc t
[MAX_UNPACK_TREES
];
767 int i
, fd
, nr_trees
= 0;
768 struct dir_struct dir
;
769 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
771 refresh_cache(REFRESH_QUIET
);
773 fd
= hold_locked_index(lock_file
, 1);
775 memset(&trees
, 0, sizeof(trees
));
776 memset(&opts
, 0, sizeof(opts
));
777 memset(&t
, 0, sizeof(t
));
778 memset(&dir
, 0, sizeof(dir
));
779 dir
.flags
|= DIR_SHOW_IGNORED
;
780 dir
.exclude_per_dir
= ".gitignore";
784 opts
.src_index
= &the_index
;
785 opts
.dst_index
= &the_index
;
787 opts
.verbose_update
= 1;
789 opts
.fn
= twoway_merge
;
790 setup_unpack_trees_porcelain(&opts
, "merge");
792 trees
[nr_trees
] = parse_tree_indirect(head
);
793 if (!trees
[nr_trees
++])
795 trees
[nr_trees
] = parse_tree_indirect(remote
);
796 if (!trees
[nr_trees
++])
798 for (i
= 0; i
< nr_trees
; i
++) {
799 parse_tree(trees
[i
]);
800 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
802 if (unpack_trees(nr_trees
, t
, &opts
))
804 if (write_cache(fd
, active_cache
, active_nr
) ||
805 commit_locked_index(lock_file
))
806 die(_("unable to write new index file"));
810 static void split_merge_strategies(const char *string
, struct strategy
**list
,
818 buf
= xstrdup(string
);
823 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
824 (*list
)[(*nr
)++].name
= xstrdup(q
);
829 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
830 (*list
)[(*nr
)++].name
= xstrdup(q
);
836 static void add_strategies(const char *string
, unsigned attr
)
838 struct strategy
*list
= NULL
;
839 int list_alloc
= 0, list_nr
= 0, i
;
841 memset(&list
, 0, sizeof(list
));
842 split_merge_strategies(string
, &list
, &list_nr
, &list_alloc
);
844 for (i
= 0; i
< list_nr
; i
++)
845 append_strategy(get_strategy(list
[i
].name
));
848 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
849 if (all_strategy
[i
].attr
& attr
)
850 append_strategy(&all_strategy
[i
]);
854 static void write_merge_msg(struct strbuf
*msg
)
856 int fd
= open(git_path("MERGE_MSG"), O_WRONLY
| O_CREAT
, 0666);
858 die_errno(_("Could not open '%s' for writing"),
859 git_path("MERGE_MSG"));
860 if (write_in_full(fd
, msg
->buf
, msg
->len
) != msg
->len
)
861 die_errno(_("Could not write to '%s'"), git_path("MERGE_MSG"));
865 static void read_merge_msg(struct strbuf
*msg
)
868 if (strbuf_read_file(msg
, git_path("MERGE_MSG"), 0) < 0)
869 die_errno(_("Could not read from '%s'"), git_path("MERGE_MSG"));
872 static void write_merge_state(void);
873 static void abort_commit(const char *err_msg
)
876 error("%s", err_msg
);
878 _("Not committing merge; use 'git commit' to complete the merge.\n"));
883 static void prepare_to_commit(void)
885 struct strbuf msg
= STRBUF_INIT
;
886 strbuf_addbuf(&msg
, &merge_msg
);
887 strbuf_addch(&msg
, '\n');
888 write_merge_msg(&msg
);
889 run_hook(get_index_file(), "prepare-commit-msg",
890 git_path("MERGE_MSG"), "merge", NULL
, NULL
);
892 if (launch_editor(git_path("MERGE_MSG"), NULL
, NULL
))
895 read_merge_msg(&msg
);
896 stripspace(&msg
, option_edit
);
898 abort_commit(_("Empty commit message."));
899 strbuf_release(&merge_msg
);
900 strbuf_addbuf(&merge_msg
, &msg
);
901 strbuf_release(&msg
);
904 static int merge_trivial(struct commit
*head
)
906 unsigned char result_tree
[20], result_commit
[20];
907 struct commit_list
*parent
= xmalloc(sizeof(*parent
));
909 write_tree_trivial(result_tree
);
910 printf(_("Wonderful.\n"));
912 parent
->next
= xmalloc(sizeof(*parent
->next
));
913 parent
->next
->item
= remoteheads
->item
;
914 parent
->next
->next
= NULL
;
916 commit_tree(merge_msg
.buf
, result_tree
, parent
, result_commit
, NULL
,
918 finish(head
, result_commit
, "In-index merge");
923 static int finish_automerge(struct commit
*head
,
924 struct commit_list
*common
,
925 unsigned char *result_tree
,
926 const char *wt_strategy
)
928 struct commit_list
*parents
= NULL
, *j
;
929 struct strbuf buf
= STRBUF_INIT
;
930 unsigned char result_commit
[20];
932 free_commit_list(common
);
933 if (allow_fast_forward
) {
934 parents
= remoteheads
;
935 commit_list_insert(head
, &parents
);
936 parents
= reduce_heads(parents
);
938 struct commit_list
**pptr
= &parents
;
940 pptr
= &commit_list_insert(head
,
942 for (j
= remoteheads
; j
; j
= j
->next
)
943 pptr
= &commit_list_insert(j
->item
, pptr
)->next
;
945 strbuf_addch(&merge_msg
, '\n');
947 free_commit_list(remoteheads
);
948 commit_tree(merge_msg
.buf
, result_tree
, parents
, result_commit
,
950 strbuf_addf(&buf
, "Merge made by the '%s' strategy.", wt_strategy
);
951 finish(head
, result_commit
, buf
.buf
);
952 strbuf_release(&buf
);
957 static int suggest_conflicts(int renormalizing
)
962 fp
= fopen(git_path("MERGE_MSG"), "a");
964 die_errno(_("Could not open '%s' for writing"),
965 git_path("MERGE_MSG"));
966 fprintf(fp
, "\nConflicts:\n");
967 for (pos
= 0; pos
< active_nr
; pos
++) {
968 struct cache_entry
*ce
= active_cache
[pos
];
971 fprintf(fp
, "\t%s\n", ce
->name
);
972 while (pos
+ 1 < active_nr
&&
974 active_cache
[pos
+ 1]->name
))
979 rerere(allow_rerere_auto
);
980 printf(_("Automatic merge failed; "
981 "fix conflicts and then commit the result.\n"));
985 static struct commit
*is_old_style_invocation(int argc
, const char **argv
,
986 const unsigned char *head
)
988 struct commit
*second_token
= NULL
;
990 unsigned char second_sha1
[20];
992 if (get_sha1(argv
[1], second_sha1
))
994 second_token
= lookup_commit_reference_gently(second_sha1
, 0);
996 die(_("'%s' is not a commit"), argv
[1]);
997 if (hashcmp(second_token
->object
.sha1
, head
))
1000 return second_token
;
1003 static int evaluate_result(void)
1006 struct rev_info rev
;
1008 /* Check how many files differ. */
1009 init_revisions(&rev
, "");
1010 setup_revisions(0, NULL
, &rev
, NULL
);
1011 rev
.diffopt
.output_format
|=
1012 DIFF_FORMAT_CALLBACK
;
1013 rev
.diffopt
.format_callback
= count_diff_files
;
1014 rev
.diffopt
.format_callback_data
= &cnt
;
1015 run_diff_files(&rev
, 0);
1018 * Check how many unmerged entries are
1021 cnt
+= count_unmerged_entries();
1027 * Pretend as if the user told us to merge with the tracking
1028 * branch we have for the upstream of the current branch
1030 static int setup_with_upstream(const char ***argv
)
1032 struct branch
*branch
= branch_get(NULL
);
1037 die(_("No current branch."));
1038 if (!branch
->remote
)
1039 die(_("No remote for the current branch."));
1040 if (!branch
->merge_nr
)
1041 die(_("No default upstream defined for the current branch."));
1043 args
= xcalloc(branch
->merge_nr
+ 1, sizeof(char *));
1044 for (i
= 0; i
< branch
->merge_nr
; i
++) {
1045 if (!branch
->merge
[i
]->dst
)
1046 die(_("No remote tracking branch for %s from %s"),
1047 branch
->merge
[i
]->src
, branch
->remote_name
);
1048 args
[i
] = branch
->merge
[i
]->dst
;
1055 static void write_merge_state(void)
1058 struct commit_list
*j
;
1059 struct strbuf buf
= STRBUF_INIT
;
1061 for (j
= remoteheads
; j
; j
= j
->next
)
1062 strbuf_addf(&buf
, "%s\n",
1063 sha1_to_hex(j
->item
->object
.sha1
));
1064 fd
= open(git_path("MERGE_HEAD"), O_WRONLY
| O_CREAT
, 0666);
1066 die_errno(_("Could not open '%s' for writing"),
1067 git_path("MERGE_HEAD"));
1068 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1069 die_errno(_("Could not write to '%s'"), git_path("MERGE_HEAD"));
1071 strbuf_addch(&merge_msg
, '\n');
1072 write_merge_msg(&merge_msg
);
1073 fd
= open(git_path("MERGE_MODE"), O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
1075 die_errno(_("Could not open '%s' for writing"),
1076 git_path("MERGE_MODE"));
1078 if (!allow_fast_forward
)
1079 strbuf_addf(&buf
, "no-ff");
1080 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1081 die_errno(_("Could not write to '%s'"), git_path("MERGE_MODE"));
1085 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
1087 unsigned char result_tree
[20];
1088 unsigned char stash
[20];
1089 unsigned char head_sha1
[20];
1090 struct commit
*head_commit
;
1091 struct strbuf buf
= STRBUF_INIT
;
1092 const char *head_arg
;
1094 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
1095 struct commit_list
*common
= NULL
;
1096 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
1097 struct commit_list
**remotes
= &remoteheads
;
1099 if (argc
== 2 && !strcmp(argv
[1], "-h"))
1100 usage_with_options(builtin_merge_usage
, builtin_merge_options
);
1103 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1106 branch
= resolve_ref("HEAD", head_sha1
, 0, &flag
);
1107 if (branch
&& !prefixcmp(branch
, "refs/heads/"))
1109 if (!branch
|| is_null_sha1(head_sha1
))
1112 head_commit
= lookup_commit_or_die(head_sha1
, "HEAD");
1114 git_config(git_merge_config
, NULL
);
1116 if (branch_mergeoptions
)
1117 parse_branch_merge_options(branch_mergeoptions
);
1118 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
1119 builtin_merge_usage
, 0);
1120 if (shortlog_len
< 0)
1121 shortlog_len
= (merge_log_config
> 0) ? merge_log_config
: 0;
1123 if (verbosity
< 0 && show_progress
== -1)
1126 if (abort_current_merge
) {
1128 const char *nargv
[] = {"reset", "--merge", NULL
};
1130 if (!file_exists(git_path("MERGE_HEAD")))
1131 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1133 /* Invoke 'git reset --merge' */
1134 return cmd_reset(nargc
, nargv
, prefix
);
1137 if (read_cache_unmerged())
1138 die_resolve_conflict("merge");
1140 if (file_exists(git_path("MERGE_HEAD"))) {
1142 * There is no unmerged entry, don't advise 'git
1143 * add/rm <file>', just 'git commit'.
1145 if (advice_resolve_conflict
)
1146 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1147 "Please, commit your changes before you can merge."));
1149 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1151 if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
1152 if (advice_resolve_conflict
)
1153 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1154 "Please, commit your changes before you can merge."));
1156 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1158 resolve_undo_clear();
1164 if (!allow_fast_forward
)
1165 die(_("You cannot combine --squash with --no-ff."));
1169 if (!allow_fast_forward
&& fast_forward_only
)
1170 die(_("You cannot combine --no-ff with --ff-only."));
1172 if (!abort_current_merge
) {
1173 if (!argc
&& default_to_upstream
)
1174 argc
= setup_with_upstream(&argv
);
1175 else if (argc
== 1 && !strcmp(argv
[0], "-"))
1179 usage_with_options(builtin_merge_usage
,
1180 builtin_merge_options
);
1183 * This could be traditional "merge <msg> HEAD <commit>..." and
1184 * the way we can tell it is to see if the second token is HEAD,
1185 * but some people might have misused the interface and used a
1186 * committish that is the same as HEAD there instead.
1187 * Traditional format never would have "-m" so it is an
1188 * additional safety measure to check for it.
1191 if (!have_message
&& head_commit
&&
1192 is_old_style_invocation(argc
, argv
, head_commit
->object
.sha1
)) {
1193 strbuf_addstr(&merge_msg
, argv
[0]);
1197 } else if (!head_commit
) {
1198 struct object
*remote_head
;
1200 * If the merged head is a valid one there is no reason
1201 * to forbid "git merge" into a branch yet to be born.
1202 * We do the same for "git pull".
1205 die(_("Can merge only exactly one commit into "
1208 die(_("Squash commit into empty head not supported yet"));
1209 if (!allow_fast_forward
)
1210 die(_("Non-fast-forward commit does not make sense into "
1212 remote_head
= want_commit(argv
[0]);
1214 die(_("%s - not something we can merge"), argv
[0]);
1215 read_empty(remote_head
->sha1
, 0);
1216 update_ref("initial pull", "HEAD", remote_head
->sha1
, NULL
, 0,
1220 struct strbuf merge_names
= STRBUF_INIT
;
1222 /* We are invoked directly as the first-class UI. */
1226 * All the rest are the commits being merged;
1227 * prepare the standard merge summary message to
1228 * be appended to the given message. If remote
1229 * is invalid we will die later in the common
1230 * codepath so we discard the error in this
1233 for (i
= 0; i
< argc
; i
++)
1234 merge_name(argv
[i
], &merge_names
);
1236 if (!have_message
|| shortlog_len
) {
1237 fmt_merge_msg(&merge_names
, &merge_msg
, !have_message
,
1240 strbuf_setlen(&merge_msg
, merge_msg
.len
- 1);
1244 if (!head_commit
|| !argc
)
1245 usage_with_options(builtin_merge_usage
,
1246 builtin_merge_options
);
1248 strbuf_addstr(&buf
, "merge");
1249 for (i
= 0; i
< argc
; i
++)
1250 strbuf_addf(&buf
, " %s", argv
[i
]);
1251 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
1254 for (i
= 0; i
< argc
; i
++) {
1256 struct commit
*commit
;
1258 o
= want_commit(argv
[i
]);
1260 die(_("%s - not something we can merge"), argv
[i
]);
1261 commit
= lookup_commit(o
->sha1
);
1262 commit
->util
= (void *)argv
[i
];
1263 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1265 strbuf_addf(&buf
, "GITHEAD_%s", sha1_to_hex(o
->sha1
));
1266 setenv(buf
.buf
, argv
[i
], 1);
1270 if (!use_strategies
) {
1271 if (!remoteheads
->next
)
1272 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
1274 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
1277 for (i
= 0; i
< use_strategies_nr
; i
++) {
1278 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
1279 allow_fast_forward
= 0;
1280 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
1284 if (!remoteheads
->next
)
1285 common
= get_merge_bases(head_commit
, remoteheads
->item
, 1);
1287 struct commit_list
*list
= remoteheads
;
1288 commit_list_insert(head_commit
, &list
);
1289 common
= get_octopus_merge_bases(list
);
1293 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head_commit
->object
.sha1
,
1294 NULL
, 0, DIE_ON_ERR
);
1297 ; /* No common ancestors found. We need a real merge. */
1298 else if (!remoteheads
->next
&& !common
->next
&&
1299 common
->item
== remoteheads
->item
) {
1301 * If head can reach all the merge then we are up to date.
1302 * but first the most common case of merging one remote.
1304 finish_up_to_date("Already up-to-date.");
1306 } else if (allow_fast_forward
&& !remoteheads
->next
&&
1308 !hashcmp(common
->item
->object
.sha1
, head_commit
->object
.sha1
)) {
1309 /* Again the most common case of merging one remote. */
1310 struct strbuf msg
= STRBUF_INIT
;
1314 strcpy(hex
, find_unique_abbrev(head_commit
->object
.sha1
, DEFAULT_ABBREV
));
1317 printf(_("Updating %s..%s\n"),
1319 find_unique_abbrev(remoteheads
->item
->object
.sha1
,
1321 strbuf_addstr(&msg
, "Fast-forward");
1324 " (no commit created; -m option ignored)");
1325 o
= want_commit(sha1_to_hex(remoteheads
->item
->object
.sha1
));
1329 if (checkout_fast_forward(head_commit
->object
.sha1
, remoteheads
->item
->object
.sha1
))
1332 finish(head_commit
, o
->sha1
, msg
.buf
);
1335 } else if (!remoteheads
->next
&& common
->next
)
1338 * We are not doing octopus and not fast-forward. Need
1341 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1343 * We are not doing octopus, not fast-forward, and have
1346 refresh_cache(REFRESH_QUIET
);
1347 if (allow_trivial
&& !fast_forward_only
) {
1348 /* See if it is really trivial. */
1349 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1350 printf(_("Trying really trivial in-index merge...\n"));
1351 if (!read_tree_trivial(common
->item
->object
.sha1
,
1352 head_commit
->object
.sha1
, remoteheads
->item
->object
.sha1
))
1353 return merge_trivial(head_commit
);
1354 printf(_("Nope.\n"));
1358 * An octopus. If we can reach all the remote we are up
1362 struct commit_list
*j
;
1364 for (j
= remoteheads
; j
; j
= j
->next
) {
1365 struct commit_list
*common_one
;
1368 * Here we *have* to calculate the individual
1369 * merge_bases again, otherwise "git merge HEAD^
1370 * HEAD^^" would be missed.
1372 common_one
= get_merge_bases(head_commit
, j
->item
, 1);
1373 if (hashcmp(common_one
->item
->object
.sha1
,
1374 j
->item
->object
.sha1
)) {
1380 finish_up_to_date("Already up-to-date. Yeeah!");
1385 if (fast_forward_only
)
1386 die(_("Not possible to fast-forward, aborting."));
1388 /* We are going to make a new commit. */
1389 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1392 * At this point, we need a real merge. No matter what strategy
1393 * we use, it would operate on the index, possibly affecting the
1394 * working tree, and when resolved cleanly, have the desired
1395 * tree in the index -- this means that the index must be in
1396 * sync with the head commit. The strategies are responsible
1399 if (use_strategies_nr
== 1 ||
1401 * Stash away the local changes so that we can try more than one.
1404 hashcpy(stash
, null_sha1
);
1406 for (i
= 0; i
< use_strategies_nr
; i
++) {
1409 printf(_("Rewinding the tree to pristine...\n"));
1410 restore_state(head_commit
->object
.sha1
, stash
);
1412 if (use_strategies_nr
!= 1)
1413 printf(_("Trying merge strategy %s...\n"),
1414 use_strategies
[i
]->name
);
1416 * Remember which strategy left the state in the working
1419 wt_strategy
= use_strategies
[i
]->name
;
1421 ret
= try_merge_strategy(use_strategies
[i
]->name
,
1422 common
, head_commit
, head_arg
);
1423 if (!option_commit
&& !ret
) {
1426 * This is necessary here just to avoid writing
1427 * the tree, but later we will *not* exit with
1428 * status code 1 because merge_was_ok is set.
1435 * The backend exits with 1 when conflicts are
1436 * left to be resolved, with 2 when it does not
1437 * handle the given merge at all.
1440 int cnt
= evaluate_result();
1442 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1443 best_strategy
= use_strategies
[i
]->name
;
1453 /* Automerge succeeded. */
1454 write_tree_trivial(result_tree
);
1455 automerge_was_ok
= 1;
1460 * If we have a resulting tree, that means the strategy module
1461 * auto resolved the merge cleanly.
1463 if (automerge_was_ok
)
1464 return finish_automerge(head_commit
, common
, result_tree
,
1468 * Pick the result from the best strategy and have the user fix
1471 if (!best_strategy
) {
1472 restore_state(head_commit
->object
.sha1
, stash
);
1473 if (use_strategies_nr
> 1)
1475 _("No merge strategy handled the merge.\n"));
1477 fprintf(stderr
, _("Merge with strategy %s failed.\n"),
1478 use_strategies
[0]->name
);
1480 } else if (best_strategy
== wt_strategy
)
1481 ; /* We already have its result in the working tree. */
1483 printf(_("Rewinding the tree to pristine...\n"));
1484 restore_state(head_commit
->object
.sha1
, stash
);
1485 printf(_("Using the %s to prepare resolving by hand.\n"),
1487 try_merge_strategy(best_strategy
, common
, head_commit
, head_arg
);
1491 finish(head_commit
, NULL
, NULL
);
1493 write_merge_state();
1496 fprintf(stderr
, _("Automatic merge went well; "
1497 "stopped before committing as requested\n"));
1500 return suggest_conflicts(option_renormalize
);