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
= -1;
52 static int allow_trivial
= 1, have_message
;
53 static int overwrite_ignore
= 1;
54 static struct strbuf merge_msg
= STRBUF_INIT
;
55 static struct commit_list
*remoteheads
;
56 static struct strategy
**use_strategies
;
57 static size_t use_strategies_nr
, use_strategies_alloc
;
58 static const char **xopts
;
59 static size_t xopts_nr
, xopts_alloc
;
60 static const char *branch
;
61 static char *branch_mergeoptions
;
62 static int option_renormalize
;
64 static int allow_rerere_auto
;
65 static int abort_current_merge
;
66 static int show_progress
= -1;
67 static int default_to_upstream
;
68 static const char *sign_commit
;
70 static struct strategy all_strategy
[] = {
71 { "recursive", DEFAULT_TWOHEAD
| NO_TRIVIAL
},
72 { "octopus", DEFAULT_OCTOPUS
},
74 { "ours", NO_FAST_FORWARD
| NO_TRIVIAL
},
75 { "subtree", NO_FAST_FORWARD
| NO_TRIVIAL
},
78 static const char *pull_twohead
, *pull_octopus
;
80 static int option_parse_message(const struct option
*opt
,
81 const char *arg
, int unset
)
83 struct strbuf
*buf
= opt
->value
;
86 strbuf_setlen(buf
, 0);
88 strbuf_addf(buf
, "%s%s", buf
->len
? "\n\n" : "", arg
);
91 return error(_("switch `m' requires a value"));
95 static struct strategy
*get_strategy(const char *name
)
99 static struct cmdnames main_cmds
, other_cmds
;
105 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
106 if (!strcmp(name
, all_strategy
[i
].name
))
107 return &all_strategy
[i
];
110 struct cmdnames not_strategies
;
113 memset(¬_strategies
, 0, sizeof(struct cmdnames
));
114 load_command_list("git-merge-", &main_cmds
, &other_cmds
);
115 for (i
= 0; i
< main_cmds
.cnt
; i
++) {
117 struct cmdname
*ent
= main_cmds
.names
[i
];
118 for (j
= 0; j
< ARRAY_SIZE(all_strategy
); j
++)
119 if (!strncmp(ent
->name
, all_strategy
[j
].name
, ent
->len
)
120 && !all_strategy
[j
].name
[ent
->len
])
123 add_cmdname(¬_strategies
, ent
->name
, ent
->len
);
125 exclude_cmds(&main_cmds
, ¬_strategies
);
127 if (!is_in_cmdlist(&main_cmds
, name
) && !is_in_cmdlist(&other_cmds
, name
)) {
128 fprintf(stderr
, _("Could not find merge strategy '%s'.\n"), name
);
129 fprintf(stderr
, _("Available strategies are:"));
130 for (i
= 0; i
< main_cmds
.cnt
; i
++)
131 fprintf(stderr
, " %s", main_cmds
.names
[i
]->name
);
132 fprintf(stderr
, ".\n");
133 if (other_cmds
.cnt
) {
134 fprintf(stderr
, _("Available custom strategies are:"));
135 for (i
= 0; i
< other_cmds
.cnt
; i
++)
136 fprintf(stderr
, " %s", other_cmds
.names
[i
]->name
);
137 fprintf(stderr
, ".\n");
142 ret
= xcalloc(1, sizeof(struct strategy
));
143 ret
->name
= xstrdup(name
);
144 ret
->attr
= NO_TRIVIAL
;
148 static void append_strategy(struct strategy
*s
)
150 ALLOC_GROW(use_strategies
, use_strategies_nr
+ 1, use_strategies_alloc
);
151 use_strategies
[use_strategies_nr
++] = s
;
154 static int option_parse_strategy(const struct option
*opt
,
155 const char *name
, int unset
)
160 append_strategy(get_strategy(name
));
164 static int option_parse_x(const struct option
*opt
,
165 const char *arg
, int unset
)
170 ALLOC_GROW(xopts
, xopts_nr
+ 1, xopts_alloc
);
171 xopts
[xopts_nr
++] = xstrdup(arg
);
175 static int option_parse_n(const struct option
*opt
,
176 const char *arg
, int unset
)
178 show_diffstat
= unset
;
182 static struct option builtin_merge_options
[] = {
183 { OPTION_CALLBACK
, 'n', NULL
, NULL
, NULL
,
184 "do not show a diffstat at the end of the merge",
185 PARSE_OPT_NOARG
, option_parse_n
},
186 OPT_BOOLEAN(0, "stat", &show_diffstat
,
187 "show a diffstat at the end of the merge"),
188 OPT_BOOLEAN(0, "summary", &show_diffstat
, "(synonym to --stat)"),
189 { OPTION_INTEGER
, 0, "log", &shortlog_len
, "n",
190 "add (at most <n>) entries from shortlog to merge commit message",
191 PARSE_OPT_OPTARG
, NULL
, DEFAULT_MERGE_LOG_LEN
},
192 OPT_BOOLEAN(0, "squash", &squash
,
193 "create a single commit instead of doing a merge"),
194 OPT_BOOLEAN(0, "commit", &option_commit
,
195 "perform a commit if the merge succeeds (default)"),
196 OPT_BOOL('e', "edit", &option_edit
,
197 "edit message before committing"),
198 OPT_BOOLEAN(0, "ff", &allow_fast_forward
,
199 "allow fast-forward (default)"),
200 OPT_BOOLEAN(0, "ff-only", &fast_forward_only
,
201 "abort if fast-forward is not possible"),
202 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto
),
203 OPT_CALLBACK('s', "strategy", &use_strategies
, "strategy",
204 "merge strategy to use", option_parse_strategy
),
205 OPT_CALLBACK('X', "strategy-option", &xopts
, "option=value",
206 "option for selected merge strategy", option_parse_x
),
207 OPT_CALLBACK('m', "message", &merge_msg
, "message",
208 "merge commit message (for a non-fast-forward merge)",
209 option_parse_message
),
210 OPT__VERBOSITY(&verbosity
),
211 OPT_BOOLEAN(0, "abort", &abort_current_merge
,
212 "abort the current in-progress merge"),
213 OPT_SET_INT(0, "progress", &show_progress
, "force progress reporting", 1),
214 { OPTION_STRING
, 'S', "gpg-sign", &sign_commit
, "key id",
215 "GPG sign commit", PARSE_OPT_OPTARG
, NULL
, (intptr_t) "" },
216 OPT_BOOLEAN(0, "overwrite-ignore", &overwrite_ignore
, "update ignored files (default)"),
220 /* Cleans up metadata that is uninteresting after a succeeded merge. */
221 static void drop_save(void)
223 unlink(git_path("MERGE_HEAD"));
224 unlink(git_path("MERGE_MSG"));
225 unlink(git_path("MERGE_MODE"));
228 static int save_state(unsigned char *stash
)
231 struct child_process cp
;
232 struct strbuf buffer
= STRBUF_INIT
;
233 const char *argv
[] = {"stash", "create", NULL
};
235 memset(&cp
, 0, sizeof(cp
));
240 if (start_command(&cp
))
241 die(_("could not run stash."));
242 len
= strbuf_read(&buffer
, cp
.out
, 1024);
245 if (finish_command(&cp
) || len
< 0)
246 die(_("stash failed"));
247 else if (!len
) /* no changes */
249 strbuf_setlen(&buffer
, buffer
.len
-1);
250 if (get_sha1(buffer
.buf
, stash
))
251 die(_("not a valid object: %s"), buffer
.buf
);
255 static void read_empty(unsigned const char *sha1
, int verbose
)
260 args
[i
++] = "read-tree";
265 args
[i
++] = EMPTY_TREE_SHA1_HEX
;
266 args
[i
++] = sha1_to_hex(sha1
);
269 if (run_command_v_opt(args
, RUN_GIT_CMD
))
270 die(_("read-tree failed"));
273 static void reset_hard(unsigned const char *sha1
, int verbose
)
278 args
[i
++] = "read-tree";
281 args
[i
++] = "--reset";
283 args
[i
++] = sha1_to_hex(sha1
);
286 if (run_command_v_opt(args
, RUN_GIT_CMD
))
287 die(_("read-tree failed"));
290 static void restore_state(const unsigned char *head
,
291 const unsigned char *stash
)
293 struct strbuf sb
= STRBUF_INIT
;
294 const char *args
[] = { "stash", "apply", NULL
, NULL
};
296 if (is_null_sha1(stash
))
301 args
[2] = sha1_to_hex(stash
);
304 * It is OK to ignore error here, for example when there was
305 * nothing to restore.
307 run_command_v_opt(args
, RUN_GIT_CMD
);
310 refresh_cache(REFRESH_QUIET
);
313 /* This is called when no merge was necessary. */
314 static void finish_up_to_date(const char *msg
)
317 printf("%s%s\n", squash
? _(" (nothing to squash)") : "", msg
);
321 static void squash_message(struct commit
*commit
)
324 struct strbuf out
= STRBUF_INIT
;
325 struct commit_list
*j
;
326 const char *filename
;
328 struct pretty_print_context ctx
= {0};
330 printf(_("Squash commit -- not updating HEAD\n"));
331 filename
= git_path("SQUASH_MSG");
332 fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
334 die_errno(_("Could not write to '%s'"), filename
);
336 init_revisions(&rev
, NULL
);
337 rev
.ignore_merges
= 1;
338 rev
.commit_format
= CMIT_FMT_MEDIUM
;
340 commit
->object
.flags
|= UNINTERESTING
;
341 add_pending_object(&rev
, &commit
->object
, NULL
);
343 for (j
= remoteheads
; j
; j
= j
->next
)
344 add_pending_object(&rev
, &j
->item
->object
, NULL
);
346 setup_revisions(0, NULL
, &rev
, NULL
);
347 if (prepare_revision_walk(&rev
))
348 die(_("revision walk setup failed"));
350 ctx
.abbrev
= rev
.abbrev
;
351 ctx
.date_mode
= rev
.date_mode
;
352 ctx
.fmt
= rev
.commit_format
;
354 strbuf_addstr(&out
, "Squashed commit of the following:\n");
355 while ((commit
= get_revision(&rev
)) != NULL
) {
356 strbuf_addch(&out
, '\n');
357 strbuf_addf(&out
, "commit %s\n",
358 sha1_to_hex(commit
->object
.sha1
));
359 pretty_print_commit(&ctx
, commit
, &out
);
361 if (write(fd
, out
.buf
, out
.len
) < 0)
362 die_errno(_("Writing SQUASH_MSG"));
364 die_errno(_("Finishing SQUASH_MSG"));
365 strbuf_release(&out
);
368 static void finish(struct commit
*head_commit
,
369 const unsigned char *new_head
, const char *msg
)
371 struct strbuf reflog_message
= STRBUF_INIT
;
372 const unsigned char *head
= head_commit
->object
.sha1
;
375 strbuf_addstr(&reflog_message
, getenv("GIT_REFLOG_ACTION"));
379 strbuf_addf(&reflog_message
, "%s: %s",
380 getenv("GIT_REFLOG_ACTION"), msg
);
383 squash_message(head_commit
);
385 if (verbosity
>= 0 && !merge_msg
.len
)
386 printf(_("No merge message -- not updating HEAD\n"));
388 const char *argv_gc_auto
[] = { "gc", "--auto", NULL
};
389 update_ref(reflog_message
.buf
, "HEAD",
393 * We ignore errors in 'gc --auto', since the
394 * user should see them.
396 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
399 if (new_head
&& show_diffstat
) {
400 struct diff_options opts
;
402 opts
.output_format
|=
403 DIFF_FORMAT_SUMMARY
| DIFF_FORMAT_DIFFSTAT
;
404 opts
.detect_rename
= DIFF_DETECT_RENAME
;
405 diff_setup_done(&opts
);
406 diff_tree_sha1(head
, new_head
, "", &opts
);
411 /* Run a post-merge hook */
412 run_hook(NULL
, "post-merge", squash
? "1" : "0", NULL
);
414 strbuf_release(&reflog_message
);
417 /* Get the name for the merge commit's message. */
418 static void merge_name(const char *remote
, struct strbuf
*msg
)
420 struct commit
*remote_head
;
421 unsigned char branch_head
[20];
422 struct strbuf buf
= STRBUF_INIT
;
423 struct strbuf bname
= STRBUF_INIT
;
428 strbuf_branchname(&bname
, remote
);
431 memset(branch_head
, 0, sizeof(branch_head
));
432 remote_head
= get_merge_parent(remote
);
434 die(_("'%s' does not point to a commit"), remote
);
436 if (dwim_ref(remote
, strlen(remote
), branch_head
, &found_ref
) > 0) {
437 if (!prefixcmp(found_ref
, "refs/heads/")) {
438 strbuf_addf(msg
, "%s\t\tbranch '%s' of .\n",
439 sha1_to_hex(branch_head
), remote
);
442 if (!prefixcmp(found_ref
, "refs/tags/")) {
443 strbuf_addf(msg
, "%s\t\ttag '%s' of .\n",
444 sha1_to_hex(branch_head
), remote
);
447 if (!prefixcmp(found_ref
, "refs/remotes/")) {
448 strbuf_addf(msg
, "%s\t\tremote-tracking branch '%s' of .\n",
449 sha1_to_hex(branch_head
), remote
);
454 /* See if remote matches <name>^^^.. or <name>~<number> */
455 for (len
= 0, ptr
= remote
+ strlen(remote
);
456 remote
< ptr
&& ptr
[-1] == '^';
463 ptr
= strrchr(remote
, '~');
465 int seen_nonzero
= 0;
468 while (*++ptr
&& isdigit(*ptr
)) {
469 seen_nonzero
|= (*ptr
!= '0');
473 len
= 0; /* not ...~<number> */
474 else if (seen_nonzero
)
477 early
= 1; /* "name~" is "name~1"! */
481 struct strbuf truname
= STRBUF_INIT
;
482 strbuf_addstr(&truname
, "refs/heads/");
483 strbuf_addstr(&truname
, remote
);
484 strbuf_setlen(&truname
, truname
.len
- len
);
485 if (ref_exists(truname
.buf
)) {
487 "%s\t\tbranch '%s'%s of .\n",
488 sha1_to_hex(remote_head
->object
.sha1
),
490 (early
? " (early part)" : ""));
491 strbuf_release(&truname
);
496 if (!strcmp(remote
, "FETCH_HEAD") &&
497 !access(git_path("FETCH_HEAD"), R_OK
)) {
498 const char *filename
;
500 struct strbuf line
= STRBUF_INIT
;
503 filename
= git_path("FETCH_HEAD");
504 fp
= fopen(filename
, "r");
506 die_errno(_("could not open '%s' for reading"),
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
->object
.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
= merge_remote_util(remoteheads
->item
)->name
;
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 if (overwrite_ignore
) {
779 memset(&dir
, 0, sizeof(dir
));
780 dir
.flags
|= DIR_SHOW_IGNORED
;
781 setup_standard_excludes(&dir
);
786 opts
.src_index
= &the_index
;
787 opts
.dst_index
= &the_index
;
789 opts
.verbose_update
= 1;
791 opts
.fn
= twoway_merge
;
792 setup_unpack_trees_porcelain(&opts
, "merge");
794 trees
[nr_trees
] = parse_tree_indirect(head
);
795 if (!trees
[nr_trees
++])
797 trees
[nr_trees
] = parse_tree_indirect(remote
);
798 if (!trees
[nr_trees
++])
800 for (i
= 0; i
< nr_trees
; i
++) {
801 parse_tree(trees
[i
]);
802 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
804 if (unpack_trees(nr_trees
, t
, &opts
))
806 if (write_cache(fd
, active_cache
, active_nr
) ||
807 commit_locked_index(lock_file
))
808 die(_("unable to write new index file"));
812 static void split_merge_strategies(const char *string
, struct strategy
**list
,
820 buf
= xstrdup(string
);
825 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
826 (*list
)[(*nr
)++].name
= xstrdup(q
);
831 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
832 (*list
)[(*nr
)++].name
= xstrdup(q
);
838 static void add_strategies(const char *string
, unsigned attr
)
840 struct strategy
*list
= NULL
;
841 int list_alloc
= 0, list_nr
= 0, i
;
843 memset(&list
, 0, sizeof(list
));
844 split_merge_strategies(string
, &list
, &list_nr
, &list_alloc
);
846 for (i
= 0; i
< list_nr
; i
++)
847 append_strategy(get_strategy(list
[i
].name
));
850 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
851 if (all_strategy
[i
].attr
& attr
)
852 append_strategy(&all_strategy
[i
]);
856 static void write_merge_msg(struct strbuf
*msg
)
858 const char *filename
= git_path("MERGE_MSG");
859 int fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
861 die_errno(_("Could not open '%s' for writing"),
863 if (write_in_full(fd
, msg
->buf
, msg
->len
) != msg
->len
)
864 die_errno(_("Could not write to '%s'"), filename
);
868 static void read_merge_msg(struct strbuf
*msg
)
870 const char *filename
= git_path("MERGE_MSG");
872 if (strbuf_read_file(msg
, filename
, 0) < 0)
873 die_errno(_("Could not read from '%s'"), filename
);
876 static void write_merge_state(void);
877 static void abort_commit(const char *err_msg
)
880 error("%s", err_msg
);
882 _("Not committing merge; use 'git commit' to complete the merge.\n"));
887 static const char merge_editor_comment
[] =
888 N_("Please enter a commit message to explain why this merge is necessary,\n"
889 "especially if it merges an updated upstream into a topic branch.\n"
891 "Lines starting with '#' will be ignored, and an empty message aborts\n"
894 static void prepare_to_commit(void)
896 struct strbuf msg
= STRBUF_INIT
;
897 const char *comment
= _(merge_editor_comment
);
898 strbuf_addbuf(&msg
, &merge_msg
);
899 strbuf_addch(&msg
, '\n');
901 strbuf_add_lines(&msg
, "# ", comment
, strlen(comment
));
902 write_merge_msg(&msg
);
903 run_hook(get_index_file(), "prepare-commit-msg",
904 git_path("MERGE_MSG"), "merge", NULL
, NULL
);
906 if (launch_editor(git_path("MERGE_MSG"), NULL
, NULL
))
909 read_merge_msg(&msg
);
910 stripspace(&msg
, option_edit
);
912 abort_commit(_("Empty commit message."));
913 strbuf_release(&merge_msg
);
914 strbuf_addbuf(&merge_msg
, &msg
);
915 strbuf_release(&msg
);
918 static int merge_trivial(struct commit
*head
)
920 unsigned char result_tree
[20], result_commit
[20];
921 struct commit_list
*parent
= xmalloc(sizeof(*parent
));
923 write_tree_trivial(result_tree
);
924 printf(_("Wonderful.\n"));
926 parent
->next
= xmalloc(sizeof(*parent
->next
));
927 parent
->next
->item
= remoteheads
->item
;
928 parent
->next
->next
= NULL
;
930 if (commit_tree(&merge_msg
, result_tree
, parent
, result_commit
, NULL
,
932 die(_("failed to write commit object"));
933 finish(head
, result_commit
, "In-index merge");
938 static int finish_automerge(struct commit
*head
,
939 struct commit_list
*common
,
940 unsigned char *result_tree
,
941 const char *wt_strategy
)
943 struct commit_list
*parents
= NULL
, *j
;
944 struct strbuf buf
= STRBUF_INIT
;
945 unsigned char result_commit
[20];
947 free_commit_list(common
);
948 if (allow_fast_forward
) {
949 parents
= remoteheads
;
950 commit_list_insert(head
, &parents
);
951 parents
= reduce_heads(parents
);
953 struct commit_list
**pptr
= &parents
;
955 pptr
= &commit_list_insert(head
,
957 for (j
= remoteheads
; j
; j
= j
->next
)
958 pptr
= &commit_list_insert(j
->item
, pptr
)->next
;
960 strbuf_addch(&merge_msg
, '\n');
962 free_commit_list(remoteheads
);
963 if (commit_tree(&merge_msg
, result_tree
, parents
, result_commit
,
965 die(_("failed to write commit object"));
966 strbuf_addf(&buf
, "Merge made by the '%s' strategy.", wt_strategy
);
967 finish(head
, result_commit
, buf
.buf
);
968 strbuf_release(&buf
);
973 static int suggest_conflicts(int renormalizing
)
975 const char *filename
;
979 filename
= git_path("MERGE_MSG");
980 fp
= fopen(filename
, "a");
982 die_errno(_("Could not open '%s' for writing"), filename
);
983 fprintf(fp
, "\nConflicts:\n");
984 for (pos
= 0; pos
< active_nr
; pos
++) {
985 struct cache_entry
*ce
= active_cache
[pos
];
988 fprintf(fp
, "\t%s\n", ce
->name
);
989 while (pos
+ 1 < active_nr
&&
991 active_cache
[pos
+ 1]->name
))
996 rerere(allow_rerere_auto
);
997 printf(_("Automatic merge failed; "
998 "fix conflicts and then commit the result.\n"));
1002 static struct commit
*is_old_style_invocation(int argc
, const char **argv
,
1003 const unsigned char *head
)
1005 struct commit
*second_token
= NULL
;
1007 unsigned char second_sha1
[20];
1009 if (get_sha1(argv
[1], second_sha1
))
1011 second_token
= lookup_commit_reference_gently(second_sha1
, 0);
1013 die(_("'%s' is not a commit"), argv
[1]);
1014 if (hashcmp(second_token
->object
.sha1
, head
))
1017 return second_token
;
1020 static int evaluate_result(void)
1023 struct rev_info rev
;
1025 /* Check how many files differ. */
1026 init_revisions(&rev
, "");
1027 setup_revisions(0, NULL
, &rev
, NULL
);
1028 rev
.diffopt
.output_format
|=
1029 DIFF_FORMAT_CALLBACK
;
1030 rev
.diffopt
.format_callback
= count_diff_files
;
1031 rev
.diffopt
.format_callback_data
= &cnt
;
1032 run_diff_files(&rev
, 0);
1035 * Check how many unmerged entries are
1038 cnt
+= count_unmerged_entries();
1044 * Pretend as if the user told us to merge with the tracking
1045 * branch we have for the upstream of the current branch
1047 static int setup_with_upstream(const char ***argv
)
1049 struct branch
*branch
= branch_get(NULL
);
1054 die(_("No current branch."));
1055 if (!branch
->remote
)
1056 die(_("No remote for the current branch."));
1057 if (!branch
->merge_nr
)
1058 die(_("No default upstream defined for the current branch."));
1060 args
= xcalloc(branch
->merge_nr
+ 1, sizeof(char *));
1061 for (i
= 0; i
< branch
->merge_nr
; i
++) {
1062 if (!branch
->merge
[i
]->dst
)
1063 die(_("No remote tracking branch for %s from %s"),
1064 branch
->merge
[i
]->src
, branch
->remote_name
);
1065 args
[i
] = branch
->merge
[i
]->dst
;
1072 static void write_merge_state(void)
1074 const char *filename
;
1076 struct commit_list
*j
;
1077 struct strbuf buf
= STRBUF_INIT
;
1079 for (j
= remoteheads
; j
; j
= j
->next
) {
1080 unsigned const char *sha1
;
1081 struct commit
*c
= j
->item
;
1082 if (c
->util
&& merge_remote_util(c
)->obj
) {
1083 sha1
= merge_remote_util(c
)->obj
->sha1
;
1085 sha1
= c
->object
.sha1
;
1087 strbuf_addf(&buf
, "%s\n", sha1_to_hex(sha1
));
1089 filename
= git_path("MERGE_HEAD");
1090 fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
1092 die_errno(_("Could not open '%s' for writing"), filename
);
1093 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1094 die_errno(_("Could not write to '%s'"), filename
);
1096 strbuf_addch(&merge_msg
, '\n');
1097 write_merge_msg(&merge_msg
);
1099 filename
= git_path("MERGE_MODE");
1100 fd
= open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
1102 die_errno(_("Could not open '%s' for writing"), filename
);
1104 if (!allow_fast_forward
)
1105 strbuf_addf(&buf
, "no-ff");
1106 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1107 die_errno(_("Could not write to '%s'"), filename
);
1111 static int default_edit_option(void)
1113 static const char name
[] = "GIT_MERGE_AUTOEDIT";
1114 const char *e
= getenv(name
);
1115 struct stat st_stdin
, st_stdout
;
1118 /* an explicit -m msg without --[no-]edit */
1122 int v
= git_config_maybe_bool(name
, e
);
1124 die("Bad value '%s' in environment '%s'", e
, name
);
1128 /* Use editor if stdin and stdout are the same and is a tty */
1129 return (!fstat(0, &st_stdin
) &&
1130 !fstat(1, &st_stdout
) &&
1131 isatty(0) && isatty(1) &&
1132 st_stdin
.st_dev
== st_stdout
.st_dev
&&
1133 st_stdin
.st_ino
== st_stdout
.st_ino
&&
1134 st_stdin
.st_mode
== st_stdout
.st_mode
);
1138 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
1140 unsigned char result_tree
[20];
1141 unsigned char stash
[20];
1142 unsigned char head_sha1
[20];
1143 struct commit
*head_commit
;
1144 struct strbuf buf
= STRBUF_INIT
;
1145 const char *head_arg
;
1146 int flag
, i
, ret
= 0;
1147 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
1148 struct commit_list
*common
= NULL
;
1149 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
1150 struct commit_list
**remotes
= &remoteheads
;
1151 void *branch_to_free
;
1153 if (argc
== 2 && !strcmp(argv
[1], "-h"))
1154 usage_with_options(builtin_merge_usage
, builtin_merge_options
);
1157 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1160 branch
= branch_to_free
= resolve_refdup("HEAD", head_sha1
, 0, &flag
);
1161 if (branch
&& !prefixcmp(branch
, "refs/heads/"))
1163 if (!branch
|| is_null_sha1(head_sha1
))
1166 head_commit
= lookup_commit_or_die(head_sha1
, "HEAD");
1168 git_config(git_merge_config
, NULL
);
1170 if (branch_mergeoptions
)
1171 parse_branch_merge_options(branch_mergeoptions
);
1172 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
1173 builtin_merge_usage
, 0);
1174 if (shortlog_len
< 0)
1175 shortlog_len
= (merge_log_config
> 0) ? merge_log_config
: 0;
1177 if (verbosity
< 0 && show_progress
== -1)
1180 if (abort_current_merge
) {
1182 const char *nargv
[] = {"reset", "--merge", NULL
};
1184 if (!file_exists(git_path("MERGE_HEAD")))
1185 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1187 /* Invoke 'git reset --merge' */
1188 ret
= cmd_reset(nargc
, nargv
, prefix
);
1192 if (read_cache_unmerged())
1193 die_resolve_conflict("merge");
1195 if (file_exists(git_path("MERGE_HEAD"))) {
1197 * There is no unmerged entry, don't advise 'git
1198 * add/rm <file>', just 'git commit'.
1200 if (advice_resolve_conflict
)
1201 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1202 "Please, commit your changes before you can merge."));
1204 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1206 if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
1207 if (advice_resolve_conflict
)
1208 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1209 "Please, commit your changes before you can merge."));
1211 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1213 resolve_undo_clear();
1219 if (!allow_fast_forward
)
1220 die(_("You cannot combine --squash with --no-ff."));
1224 if (!allow_fast_forward
&& fast_forward_only
)
1225 die(_("You cannot combine --no-ff with --ff-only."));
1227 if (!abort_current_merge
) {
1229 if (default_to_upstream
)
1230 argc
= setup_with_upstream(&argv
);
1232 die(_("No commit specified and merge.defaultToUpstream not set."));
1233 } else if (argc
== 1 && !strcmp(argv
[0], "-"))
1237 usage_with_options(builtin_merge_usage
,
1238 builtin_merge_options
);
1241 * This could be traditional "merge <msg> HEAD <commit>..." and
1242 * the way we can tell it is to see if the second token is HEAD,
1243 * but some people might have misused the interface and used a
1244 * committish that is the same as HEAD there instead.
1245 * Traditional format never would have "-m" so it is an
1246 * additional safety measure to check for it.
1249 if (!have_message
&& head_commit
&&
1250 is_old_style_invocation(argc
, argv
, head_commit
->object
.sha1
)) {
1251 strbuf_addstr(&merge_msg
, argv
[0]);
1255 } else if (!head_commit
) {
1256 struct commit
*remote_head
;
1258 * If the merged head is a valid one there is no reason
1259 * to forbid "git merge" into a branch yet to be born.
1260 * We do the same for "git pull".
1263 die(_("Can merge only exactly one commit into "
1266 die(_("Squash commit into empty head not supported yet"));
1267 if (!allow_fast_forward
)
1268 die(_("Non-fast-forward commit does not make sense into "
1270 remote_head
= get_merge_parent(argv
[0]);
1272 die(_("%s - not something we can merge"), argv
[0]);
1273 read_empty(remote_head
->object
.sha1
, 0);
1274 update_ref("initial pull", "HEAD", remote_head
->object
.sha1
,
1275 NULL
, 0, DIE_ON_ERR
);
1278 struct strbuf merge_names
= STRBUF_INIT
;
1280 /* We are invoked directly as the first-class UI. */
1284 * All the rest are the commits being merged; prepare
1285 * the standard merge summary message to be appended
1286 * to the given message.
1288 for (i
= 0; i
< argc
; i
++)
1289 merge_name(argv
[i
], &merge_names
);
1291 if (!have_message
|| shortlog_len
) {
1292 struct fmt_merge_msg_opts opts
;
1293 memset(&opts
, 0, sizeof(opts
));
1294 opts
.add_title
= !have_message
;
1295 opts
.shortlog_len
= shortlog_len
;
1297 fmt_merge_msg(&merge_names
, &merge_msg
, &opts
);
1299 strbuf_setlen(&merge_msg
, merge_msg
.len
- 1);
1303 if (!head_commit
|| !argc
)
1304 usage_with_options(builtin_merge_usage
,
1305 builtin_merge_options
);
1307 strbuf_addstr(&buf
, "merge");
1308 for (i
= 0; i
< argc
; i
++)
1309 strbuf_addf(&buf
, " %s", argv
[i
]);
1310 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
1313 for (i
= 0; i
< argc
; i
++) {
1314 struct commit
*commit
= get_merge_parent(argv
[i
]);
1316 die(_("%s - not something we can merge"), argv
[i
]);
1317 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1318 strbuf_addf(&buf
, "GITHEAD_%s",
1319 sha1_to_hex(commit
->object
.sha1
));
1320 setenv(buf
.buf
, argv
[i
], 1);
1322 if (!fast_forward_only
&&
1323 merge_remote_util(commit
) &&
1324 merge_remote_util(commit
)->obj
&&
1325 merge_remote_util(commit
)->obj
->type
== OBJ_TAG
) {
1326 if (option_edit
< 0)
1327 option_edit
= default_edit_option();
1328 allow_fast_forward
= 0;
1332 if (option_edit
< 0)
1335 if (!use_strategies
) {
1336 if (!remoteheads
->next
)
1337 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
1339 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
1342 for (i
= 0; i
< use_strategies_nr
; i
++) {
1343 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
1344 allow_fast_forward
= 0;
1345 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
1349 if (!remoteheads
->next
)
1350 common
= get_merge_bases(head_commit
, remoteheads
->item
, 1);
1352 struct commit_list
*list
= remoteheads
;
1353 commit_list_insert(head_commit
, &list
);
1354 common
= get_octopus_merge_bases(list
);
1358 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head_commit
->object
.sha1
,
1359 NULL
, 0, DIE_ON_ERR
);
1362 ; /* No common ancestors found. We need a real merge. */
1363 else if (!remoteheads
->next
&& !common
->next
&&
1364 common
->item
== remoteheads
->item
) {
1366 * If head can reach all the merge then we are up to date.
1367 * but first the most common case of merging one remote.
1369 finish_up_to_date("Already up-to-date.");
1371 } else if (allow_fast_forward
&& !remoteheads
->next
&&
1373 !hashcmp(common
->item
->object
.sha1
, head_commit
->object
.sha1
)) {
1374 /* Again the most common case of merging one remote. */
1375 struct strbuf msg
= STRBUF_INIT
;
1376 struct commit
*commit
;
1379 strcpy(hex
, find_unique_abbrev(head_commit
->object
.sha1
, DEFAULT_ABBREV
));
1382 printf(_("Updating %s..%s\n"),
1384 find_unique_abbrev(remoteheads
->item
->object
.sha1
,
1386 strbuf_addstr(&msg
, "Fast-forward");
1389 " (no commit created; -m option ignored)");
1390 commit
= remoteheads
->item
;
1396 if (checkout_fast_forward(head_commit
->object
.sha1
,
1397 commit
->object
.sha1
)) {
1402 finish(head_commit
, commit
->object
.sha1
, msg
.buf
);
1405 } else if (!remoteheads
->next
&& common
->next
)
1408 * We are not doing octopus and not fast-forward. Need
1411 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1413 * We are not doing octopus, not fast-forward, and have
1416 refresh_cache(REFRESH_QUIET
);
1417 if (allow_trivial
&& !fast_forward_only
) {
1418 /* See if it is really trivial. */
1419 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1420 printf(_("Trying really trivial in-index merge...\n"));
1421 if (!read_tree_trivial(common
->item
->object
.sha1
,
1422 head_commit
->object
.sha1
,
1423 remoteheads
->item
->object
.sha1
)) {
1424 ret
= merge_trivial(head_commit
);
1427 printf(_("Nope.\n"));
1431 * An octopus. If we can reach all the remote we are up
1435 struct commit_list
*j
;
1437 for (j
= remoteheads
; j
; j
= j
->next
) {
1438 struct commit_list
*common_one
;
1441 * Here we *have* to calculate the individual
1442 * merge_bases again, otherwise "git merge HEAD^
1443 * HEAD^^" would be missed.
1445 common_one
= get_merge_bases(head_commit
, j
->item
, 1);
1446 if (hashcmp(common_one
->item
->object
.sha1
,
1447 j
->item
->object
.sha1
)) {
1453 finish_up_to_date("Already up-to-date. Yeeah!");
1458 if (fast_forward_only
)
1459 die(_("Not possible to fast-forward, aborting."));
1461 /* We are going to make a new commit. */
1462 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1465 * At this point, we need a real merge. No matter what strategy
1466 * we use, it would operate on the index, possibly affecting the
1467 * working tree, and when resolved cleanly, have the desired
1468 * tree in the index -- this means that the index must be in
1469 * sync with the head commit. The strategies are responsible
1472 if (use_strategies_nr
== 1 ||
1474 * Stash away the local changes so that we can try more than one.
1477 hashcpy(stash
, null_sha1
);
1479 for (i
= 0; i
< use_strategies_nr
; i
++) {
1482 printf(_("Rewinding the tree to pristine...\n"));
1483 restore_state(head_commit
->object
.sha1
, stash
);
1485 if (use_strategies_nr
!= 1)
1486 printf(_("Trying merge strategy %s...\n"),
1487 use_strategies
[i
]->name
);
1489 * Remember which strategy left the state in the working
1492 wt_strategy
= use_strategies
[i
]->name
;
1494 ret
= try_merge_strategy(use_strategies
[i
]->name
,
1495 common
, head_commit
, head_arg
);
1496 if (!option_commit
&& !ret
) {
1499 * This is necessary here just to avoid writing
1500 * the tree, but later we will *not* exit with
1501 * status code 1 because merge_was_ok is set.
1508 * The backend exits with 1 when conflicts are
1509 * left to be resolved, with 2 when it does not
1510 * handle the given merge at all.
1513 int cnt
= evaluate_result();
1515 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1516 best_strategy
= use_strategies
[i
]->name
;
1526 /* Automerge succeeded. */
1527 write_tree_trivial(result_tree
);
1528 automerge_was_ok
= 1;
1533 * If we have a resulting tree, that means the strategy module
1534 * auto resolved the merge cleanly.
1536 if (automerge_was_ok
) {
1537 ret
= finish_automerge(head_commit
, common
, result_tree
,
1543 * Pick the result from the best strategy and have the user fix
1546 if (!best_strategy
) {
1547 restore_state(head_commit
->object
.sha1
, stash
);
1548 if (use_strategies_nr
> 1)
1550 _("No merge strategy handled the merge.\n"));
1552 fprintf(stderr
, _("Merge with strategy %s failed.\n"),
1553 use_strategies
[0]->name
);
1556 } else if (best_strategy
== wt_strategy
)
1557 ; /* We already have its result in the working tree. */
1559 printf(_("Rewinding the tree to pristine...\n"));
1560 restore_state(head_commit
->object
.sha1
, stash
);
1561 printf(_("Using the %s to prepare resolving by hand.\n"),
1563 try_merge_strategy(best_strategy
, common
, head_commit
, head_arg
);
1567 finish(head_commit
, NULL
, NULL
);
1569 write_merge_state();
1572 fprintf(stderr
, _("Automatic merge went well; "
1573 "stopped before committing as requested\n"));
1575 ret
= suggest_conflicts(option_renormalize
);
1578 free(branch_to_free
);