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"
31 #define DEFAULT_TWOHEAD (1<<0)
32 #define DEFAULT_OCTOPUS (1<<1)
33 #define NO_FAST_FORWARD (1<<2)
34 #define NO_TRIVIAL (1<<3)
41 static const char * const builtin_merge_usage
[] = {
42 "git merge [options] [<commit>...]",
43 "git merge [options] <msg> HEAD <commit>",
48 static int show_diffstat
= 1, shortlog_len
= -1, squash
;
49 static int option_commit
= 1, allow_fast_forward
= 1;
50 static int fast_forward_only
, option_edit
;
51 static int allow_trivial
= 1, have_message
;
52 static int overwrite_ignore
= 1;
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
;
68 static struct strategy all_strategy
[] = {
69 { "recursive", DEFAULT_TWOHEAD
| NO_TRIVIAL
},
70 { "octopus", DEFAULT_OCTOPUS
},
72 { "ours", NO_FAST_FORWARD
| NO_TRIVIAL
},
73 { "subtree", NO_FAST_FORWARD
| NO_TRIVIAL
},
76 static const char *pull_twohead
, *pull_octopus
;
78 static int option_parse_message(const struct option
*opt
,
79 const char *arg
, int unset
)
81 struct strbuf
*buf
= opt
->value
;
84 strbuf_setlen(buf
, 0);
86 strbuf_addf(buf
, "%s%s", buf
->len
? "\n\n" : "", arg
);
89 return error(_("switch `m' requires a value"));
93 static struct strategy
*get_strategy(const char *name
)
97 static struct cmdnames main_cmds
, other_cmds
;
103 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
104 if (!strcmp(name
, all_strategy
[i
].name
))
105 return &all_strategy
[i
];
108 struct cmdnames not_strategies
;
111 memset(¬_strategies
, 0, sizeof(struct cmdnames
));
112 load_command_list("git-merge-", &main_cmds
, &other_cmds
);
113 for (i
= 0; i
< main_cmds
.cnt
; i
++) {
115 struct cmdname
*ent
= main_cmds
.names
[i
];
116 for (j
= 0; j
< ARRAY_SIZE(all_strategy
); j
++)
117 if (!strncmp(ent
->name
, all_strategy
[j
].name
, ent
->len
)
118 && !all_strategy
[j
].name
[ent
->len
])
121 add_cmdname(¬_strategies
, ent
->name
, ent
->len
);
123 exclude_cmds(&main_cmds
, ¬_strategies
);
125 if (!is_in_cmdlist(&main_cmds
, name
) && !is_in_cmdlist(&other_cmds
, name
)) {
126 fprintf(stderr
, _("Could not find merge strategy '%s'.\n"), name
);
127 fprintf(stderr
, _("Available strategies are:"));
128 for (i
= 0; i
< main_cmds
.cnt
; i
++)
129 fprintf(stderr
, " %s", main_cmds
.names
[i
]->name
);
130 fprintf(stderr
, ".\n");
131 if (other_cmds
.cnt
) {
132 fprintf(stderr
, _("Available custom strategies are:"));
133 for (i
= 0; i
< other_cmds
.cnt
; i
++)
134 fprintf(stderr
, " %s", other_cmds
.names
[i
]->name
);
135 fprintf(stderr
, ".\n");
140 ret
= xcalloc(1, sizeof(struct strategy
));
141 ret
->name
= xstrdup(name
);
142 ret
->attr
= NO_TRIVIAL
;
146 static void append_strategy(struct strategy
*s
)
148 ALLOC_GROW(use_strategies
, use_strategies_nr
+ 1, use_strategies_alloc
);
149 use_strategies
[use_strategies_nr
++] = s
;
152 static int option_parse_strategy(const struct option
*opt
,
153 const char *name
, int unset
)
158 append_strategy(get_strategy(name
));
162 static int option_parse_x(const struct option
*opt
,
163 const char *arg
, int unset
)
168 ALLOC_GROW(xopts
, xopts_nr
+ 1, xopts_alloc
);
169 xopts
[xopts_nr
++] = xstrdup(arg
);
173 static int option_parse_n(const struct option
*opt
,
174 const char *arg
, int unset
)
176 show_diffstat
= unset
;
180 static struct option builtin_merge_options
[] = {
181 { OPTION_CALLBACK
, 'n', NULL
, NULL
, NULL
,
182 "do not show a diffstat at the end of the merge",
183 PARSE_OPT_NOARG
, option_parse_n
},
184 OPT_BOOLEAN(0, "stat", &show_diffstat
,
185 "show a diffstat at the end of the merge"),
186 OPT_BOOLEAN(0, "summary", &show_diffstat
, "(synonym to --stat)"),
187 { OPTION_INTEGER
, 0, "log", &shortlog_len
, "n",
188 "add (at most <n>) entries from shortlog to merge commit message",
189 PARSE_OPT_OPTARG
, NULL
, DEFAULT_MERGE_LOG_LEN
},
190 OPT_BOOLEAN(0, "squash", &squash
,
191 "create a single commit instead of doing a merge"),
192 OPT_BOOLEAN(0, "commit", &option_commit
,
193 "perform a commit if the merge succeeds (default)"),
194 OPT_BOOLEAN('e', "edit", &option_edit
,
195 "edit message before committing"),
196 OPT_BOOLEAN(0, "ff", &allow_fast_forward
,
197 "allow fast-forward (default)"),
198 OPT_BOOLEAN(0, "ff-only", &fast_forward_only
,
199 "abort if fast-forward is not possible"),
200 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto
),
201 OPT_CALLBACK('s', "strategy", &use_strategies
, "strategy",
202 "merge strategy to use", option_parse_strategy
),
203 OPT_CALLBACK('X', "strategy-option", &xopts
, "option=value",
204 "option for selected merge strategy", option_parse_x
),
205 OPT_CALLBACK('m', "message", &merge_msg
, "message",
206 "merge commit message (for a non-fast-forward merge)",
207 option_parse_message
),
208 OPT__VERBOSITY(&verbosity
),
209 OPT_BOOLEAN(0, "abort", &abort_current_merge
,
210 "abort the current in-progress merge"),
211 OPT_SET_INT(0, "progress", &show_progress
, "force progress reporting", 1),
212 OPT_BOOLEAN(0, "overwrite-ignore", &overwrite_ignore
, "update ignored files (default)"),
216 /* Cleans up metadata that is uninteresting after a succeeded merge. */
217 static void drop_save(void)
219 unlink(git_path("MERGE_HEAD"));
220 unlink(git_path("MERGE_MSG"));
221 unlink(git_path("MERGE_MODE"));
224 static int save_state(unsigned char *stash
)
227 struct child_process cp
;
228 struct strbuf buffer
= STRBUF_INIT
;
229 const char *argv
[] = {"stash", "create", NULL
};
231 memset(&cp
, 0, sizeof(cp
));
236 if (start_command(&cp
))
237 die(_("could not run stash."));
238 len
= strbuf_read(&buffer
, cp
.out
, 1024);
241 if (finish_command(&cp
) || len
< 0)
242 die(_("stash failed"));
243 else if (!len
) /* no changes */
245 strbuf_setlen(&buffer
, buffer
.len
-1);
246 if (get_sha1(buffer
.buf
, stash
))
247 die(_("not a valid object: %s"), buffer
.buf
);
251 static void read_empty(unsigned const char *sha1
, int verbose
)
256 args
[i
++] = "read-tree";
261 args
[i
++] = EMPTY_TREE_SHA1_HEX
;
262 args
[i
++] = sha1_to_hex(sha1
);
265 if (run_command_v_opt(args
, RUN_GIT_CMD
))
266 die(_("read-tree failed"));
269 static void reset_hard(unsigned const char *sha1
, int verbose
)
274 args
[i
++] = "read-tree";
277 args
[i
++] = "--reset";
279 args
[i
++] = sha1_to_hex(sha1
);
282 if (run_command_v_opt(args
, RUN_GIT_CMD
))
283 die(_("read-tree failed"));
286 static void restore_state(const unsigned char *head
,
287 const unsigned char *stash
)
289 struct strbuf sb
= STRBUF_INIT
;
290 const char *args
[] = { "stash", "apply", NULL
, NULL
};
292 if (is_null_sha1(stash
))
297 args
[2] = sha1_to_hex(stash
);
300 * It is OK to ignore error here, for example when there was
301 * nothing to restore.
303 run_command_v_opt(args
, RUN_GIT_CMD
);
306 refresh_cache(REFRESH_QUIET
);
309 /* This is called when no merge was necessary. */
310 static void finish_up_to_date(const char *msg
)
313 printf("%s%s\n", squash
? _(" (nothing to squash)") : "", msg
);
317 static void squash_message(struct commit
*commit
)
320 struct strbuf out
= STRBUF_INIT
;
321 struct commit_list
*j
;
322 const char *filename
;
324 struct pretty_print_context ctx
= {0};
326 printf(_("Squash commit -- not updating HEAD\n"));
327 filename
= git_path("SQUASH_MSG");
328 fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
330 die_errno(_("Could not write to '%s'"), filename
);
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 /* Get the name for the merge commit's message. */
415 static void merge_name(const char *remote
, struct strbuf
*msg
)
417 struct commit
*remote_head
;
418 unsigned char branch_head
[20];
419 struct strbuf buf
= STRBUF_INIT
;
420 struct strbuf bname
= STRBUF_INIT
;
425 strbuf_branchname(&bname
, remote
);
428 memset(branch_head
, 0, sizeof(branch_head
));
429 remote_head
= get_merge_parent(remote
);
431 die(_("'%s' does not point to a commit"), remote
);
433 if (dwim_ref(remote
, strlen(remote
), branch_head
, &found_ref
) > 0) {
434 if (!prefixcmp(found_ref
, "refs/heads/")) {
435 strbuf_addf(msg
, "%s\t\tbranch '%s' of .\n",
436 sha1_to_hex(branch_head
), remote
);
439 if (!prefixcmp(found_ref
, "refs/tags/")) {
440 strbuf_addf(msg
, "%s\t\ttag '%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 (ref_exists(truname
.buf
)) {
484 "%s\t\tbranch '%s'%s of .\n",
485 sha1_to_hex(remote_head
->object
.sha1
),
487 (early
? " (early part)" : ""));
488 strbuf_release(&truname
);
493 if (!strcmp(remote
, "FETCH_HEAD") &&
494 !access(git_path("FETCH_HEAD"), R_OK
)) {
495 const char *filename
;
497 struct strbuf line
= STRBUF_INIT
;
500 filename
= git_path("FETCH_HEAD");
501 fp
= fopen(filename
, "r");
503 die_errno(_("could not open '%s' for reading"),
505 strbuf_getline(&line
, fp
, '\n');
507 ptr
= strstr(line
.buf
, "\tnot-for-merge\t");
509 strbuf_remove(&line
, ptr
-line
.buf
+1, 13);
510 strbuf_addbuf(msg
, &line
);
511 strbuf_release(&line
);
514 strbuf_addf(msg
, "%s\t\tcommit '%s'\n",
515 sha1_to_hex(remote_head
->object
.sha1
), remote
);
517 strbuf_release(&buf
);
518 strbuf_release(&bname
);
521 static void parse_branch_merge_options(char *bmo
)
528 argc
= split_cmdline(bmo
, &argv
);
530 die(_("Bad branch.%s.mergeoptions string: %s"), branch
,
531 split_cmdline_strerror(argc
));
532 argv
= xrealloc(argv
, sizeof(*argv
) * (argc
+ 2));
533 memmove(argv
+ 1, argv
, sizeof(*argv
) * (argc
+ 1));
535 argv
[0] = "branch.*.mergeoptions";
536 parse_options(argc
, argv
, NULL
, builtin_merge_options
,
537 builtin_merge_usage
, 0);
541 static int git_merge_config(const char *k
, const char *v
, void *cb
)
545 if (branch
&& !prefixcmp(k
, "branch.") &&
546 !prefixcmp(k
+ 7, branch
) &&
547 !strcmp(k
+ 7 + strlen(branch
), ".mergeoptions")) {
548 free(branch_mergeoptions
);
549 branch_mergeoptions
= xstrdup(v
);
553 if (!strcmp(k
, "merge.diffstat") || !strcmp(k
, "merge.stat"))
554 show_diffstat
= git_config_bool(k
, v
);
555 else if (!strcmp(k
, "pull.twohead"))
556 return git_config_string(&pull_twohead
, k
, v
);
557 else if (!strcmp(k
, "pull.octopus"))
558 return git_config_string(&pull_octopus
, k
, v
);
559 else if (!strcmp(k
, "merge.renormalize"))
560 option_renormalize
= git_config_bool(k
, v
);
561 else if (!strcmp(k
, "merge.ff")) {
562 int boolval
= git_config_maybe_bool(k
, v
);
564 allow_fast_forward
= boolval
;
565 } else if (v
&& !strcmp(v
, "only")) {
566 allow_fast_forward
= 1;
567 fast_forward_only
= 1;
568 } /* do not barf on values from future versions of git */
570 } else if (!strcmp(k
, "merge.defaulttoupstream")) {
571 default_to_upstream
= git_config_bool(k
, v
);
574 status
= fmt_merge_msg_config(k
, v
, cb
);
577 return git_diff_ui_config(k
, v
, cb
);
580 static int read_tree_trivial(unsigned char *common
, unsigned char *head
,
584 struct tree
*trees
[MAX_UNPACK_TREES
];
585 struct tree_desc t
[MAX_UNPACK_TREES
];
586 struct unpack_trees_options opts
;
588 memset(&opts
, 0, sizeof(opts
));
590 opts
.src_index
= &the_index
;
591 opts
.dst_index
= &the_index
;
593 opts
.verbose_update
= 1;
594 opts
.trivial_merges_only
= 1;
596 trees
[nr_trees
] = parse_tree_indirect(common
);
597 if (!trees
[nr_trees
++])
599 trees
[nr_trees
] = parse_tree_indirect(head
);
600 if (!trees
[nr_trees
++])
602 trees
[nr_trees
] = parse_tree_indirect(one
);
603 if (!trees
[nr_trees
++])
605 opts
.fn
= threeway_merge
;
606 cache_tree_free(&active_cache_tree
);
607 for (i
= 0; i
< nr_trees
; i
++) {
608 parse_tree(trees
[i
]);
609 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
611 if (unpack_trees(nr_trees
, t
, &opts
))
616 static void write_tree_trivial(unsigned char *sha1
)
618 if (write_cache_as_tree(sha1
, 0, NULL
))
619 die(_("git write-tree failed to write a tree"));
622 static const char *merge_argument(struct commit
*commit
)
625 return sha1_to_hex(commit
->object
.sha1
);
627 return EMPTY_TREE_SHA1_HEX
;
630 int try_merge_command(const char *strategy
, size_t xopts_nr
,
631 const char **xopts
, struct commit_list
*common
,
632 const char *head_arg
, struct commit_list
*remotes
)
635 int i
= 0, x
= 0, ret
;
636 struct commit_list
*j
;
637 struct strbuf buf
= STRBUF_INIT
;
639 args
= xmalloc((4 + xopts_nr
+ commit_list_count(common
) +
640 commit_list_count(remotes
)) * sizeof(char *));
641 strbuf_addf(&buf
, "merge-%s", strategy
);
643 for (x
= 0; x
< xopts_nr
; x
++) {
644 char *s
= xmalloc(strlen(xopts
[x
])+2+1);
646 strcpy(s
+2, xopts
[x
]);
649 for (j
= common
; j
; j
= j
->next
)
650 args
[i
++] = xstrdup(merge_argument(j
->item
));
652 args
[i
++] = head_arg
;
653 for (j
= remotes
; j
; j
= j
->next
)
654 args
[i
++] = xstrdup(merge_argument(j
->item
));
656 ret
= run_command_v_opt(args
, RUN_GIT_CMD
);
657 strbuf_release(&buf
);
659 for (x
= 0; x
< xopts_nr
; x
++)
660 free((void *)args
[i
++]);
661 for (j
= common
; j
; j
= j
->next
)
662 free((void *)args
[i
++]);
664 for (j
= remotes
; j
; j
= j
->next
)
665 free((void *)args
[i
++]);
668 if (read_cache() < 0)
669 die(_("failed to read the cache"));
670 resolve_undo_clear();
675 static int try_merge_strategy(const char *strategy
, struct commit_list
*common
,
676 struct commit
*head
, const char *head_arg
)
679 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
681 index_fd
= hold_locked_index(lock
, 1);
682 refresh_cache(REFRESH_QUIET
);
683 if (active_cache_changed
&&
684 (write_cache(index_fd
, active_cache
, active_nr
) ||
685 commit_locked_index(lock
)))
686 return error(_("Unable to write index."));
687 rollback_lock_file(lock
);
689 if (!strcmp(strategy
, "recursive") || !strcmp(strategy
, "subtree")) {
691 struct commit
*result
;
692 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
694 struct commit_list
*reversed
= NULL
;
695 struct merge_options o
;
696 struct commit_list
*j
;
698 if (remoteheads
->next
) {
699 error(_("Not handling anything other than two heads merge."));
703 init_merge_options(&o
);
704 if (!strcmp(strategy
, "subtree"))
705 o
.subtree_shift
= "";
707 o
.renormalize
= option_renormalize
;
708 o
.show_rename_progress
=
709 show_progress
== -1 ? isatty(2) : show_progress
;
711 for (x
= 0; x
< xopts_nr
; x
++)
712 if (parse_merge_opt(&o
, xopts
[x
]))
713 die(_("Unknown option for merge-recursive: -X%s"), xopts
[x
]);
715 o
.branch1
= head_arg
;
716 o
.branch2
= merge_remote_util(remoteheads
->item
)->name
;
718 for (j
= common
; j
; j
= j
->next
)
719 commit_list_insert(j
->item
, &reversed
);
721 index_fd
= hold_locked_index(lock
, 1);
722 clean
= merge_recursive(&o
, head
,
723 remoteheads
->item
, reversed
, &result
);
724 if (active_cache_changed
&&
725 (write_cache(index_fd
, active_cache
, active_nr
) ||
726 commit_locked_index(lock
)))
727 die (_("unable to write %s"), get_index_file());
728 rollback_lock_file(lock
);
729 return clean
? 0 : 1;
731 return try_merge_command(strategy
, xopts_nr
, xopts
,
732 common
, head_arg
, remoteheads
);
736 static void count_diff_files(struct diff_queue_struct
*q
,
737 struct diff_options
*opt
, void *data
)
744 static int count_unmerged_entries(void)
748 for (i
= 0; i
< active_nr
; i
++)
749 if (ce_stage(active_cache
[i
]))
755 int checkout_fast_forward(const unsigned char *head
, const unsigned char *remote
)
757 struct tree
*trees
[MAX_UNPACK_TREES
];
758 struct unpack_trees_options opts
;
759 struct tree_desc t
[MAX_UNPACK_TREES
];
760 int i
, fd
, nr_trees
= 0;
761 struct dir_struct dir
;
762 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
764 refresh_cache(REFRESH_QUIET
);
766 fd
= hold_locked_index(lock_file
, 1);
768 memset(&trees
, 0, sizeof(trees
));
769 memset(&opts
, 0, sizeof(opts
));
770 memset(&t
, 0, sizeof(t
));
771 if (overwrite_ignore
) {
772 memset(&dir
, 0, sizeof(dir
));
773 dir
.flags
|= DIR_SHOW_IGNORED
;
774 setup_standard_excludes(&dir
);
779 opts
.src_index
= &the_index
;
780 opts
.dst_index
= &the_index
;
782 opts
.verbose_update
= 1;
784 opts
.fn
= twoway_merge
;
785 setup_unpack_trees_porcelain(&opts
, "merge");
787 trees
[nr_trees
] = parse_tree_indirect(head
);
788 if (!trees
[nr_trees
++])
790 trees
[nr_trees
] = parse_tree_indirect(remote
);
791 if (!trees
[nr_trees
++])
793 for (i
= 0; i
< nr_trees
; i
++) {
794 parse_tree(trees
[i
]);
795 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
797 if (unpack_trees(nr_trees
, t
, &opts
))
799 if (write_cache(fd
, active_cache
, active_nr
) ||
800 commit_locked_index(lock_file
))
801 die(_("unable to write new index file"));
805 static void split_merge_strategies(const char *string
, struct strategy
**list
,
813 buf
= xstrdup(string
);
818 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
819 (*list
)[(*nr
)++].name
= xstrdup(q
);
824 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
825 (*list
)[(*nr
)++].name
= xstrdup(q
);
831 static void add_strategies(const char *string
, unsigned attr
)
833 struct strategy
*list
= NULL
;
834 int list_alloc
= 0, list_nr
= 0, i
;
836 memset(&list
, 0, sizeof(list
));
837 split_merge_strategies(string
, &list
, &list_nr
, &list_alloc
);
839 for (i
= 0; i
< list_nr
; i
++)
840 append_strategy(get_strategy(list
[i
].name
));
843 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
844 if (all_strategy
[i
].attr
& attr
)
845 append_strategy(&all_strategy
[i
]);
849 static void write_merge_msg(struct strbuf
*msg
)
851 const char *filename
= git_path("MERGE_MSG");
852 int fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
854 die_errno(_("Could not open '%s' for writing"),
856 if (write_in_full(fd
, msg
->buf
, msg
->len
) != msg
->len
)
857 die_errno(_("Could not write to '%s'"), filename
);
861 static void read_merge_msg(struct strbuf
*msg
)
863 const char *filename
= git_path("MERGE_MSG");
865 if (strbuf_read_file(msg
, filename
, 0) < 0)
866 die_errno(_("Could not read from '%s'"), filename
);
869 static void write_merge_state(void);
870 static void abort_commit(const char *err_msg
)
873 error("%s", err_msg
);
875 _("Not committing merge; use 'git commit' to complete the merge.\n"));
880 static void prepare_to_commit(void)
882 struct strbuf msg
= STRBUF_INIT
;
883 strbuf_addbuf(&msg
, &merge_msg
);
884 strbuf_addch(&msg
, '\n');
885 write_merge_msg(&msg
);
886 run_hook(get_index_file(), "prepare-commit-msg",
887 git_path("MERGE_MSG"), "merge", NULL
, NULL
);
889 if (launch_editor(git_path("MERGE_MSG"), NULL
, NULL
))
892 read_merge_msg(&msg
);
893 stripspace(&msg
, option_edit
);
895 abort_commit(_("Empty commit message."));
896 strbuf_release(&merge_msg
);
897 strbuf_addbuf(&merge_msg
, &msg
);
898 strbuf_release(&msg
);
901 static int merge_trivial(struct commit
*head
)
903 unsigned char result_tree
[20], result_commit
[20];
904 struct commit_list
*parent
= xmalloc(sizeof(*parent
));
906 write_tree_trivial(result_tree
);
907 printf(_("Wonderful.\n"));
909 parent
->next
= xmalloc(sizeof(*parent
->next
));
910 parent
->next
->item
= remoteheads
->item
;
911 parent
->next
->next
= NULL
;
913 commit_tree(merge_msg
.buf
, result_tree
, parent
, result_commit
, NULL
);
914 finish(head
, result_commit
, "In-index merge");
919 static int finish_automerge(struct commit
*head
,
920 struct commit_list
*common
,
921 unsigned char *result_tree
,
922 const char *wt_strategy
)
924 struct commit_list
*parents
= NULL
, *j
;
925 struct strbuf buf
= STRBUF_INIT
;
926 unsigned char result_commit
[20];
928 free_commit_list(common
);
929 if (allow_fast_forward
) {
930 parents
= remoteheads
;
931 commit_list_insert(head
, &parents
);
932 parents
= reduce_heads(parents
);
934 struct commit_list
**pptr
= &parents
;
936 pptr
= &commit_list_insert(head
,
938 for (j
= remoteheads
; j
; j
= j
->next
)
939 pptr
= &commit_list_insert(j
->item
, pptr
)->next
;
941 strbuf_addch(&merge_msg
, '\n');
943 free_commit_list(remoteheads
);
944 commit_tree(merge_msg
.buf
, result_tree
, parents
, result_commit
, NULL
);
945 strbuf_addf(&buf
, "Merge made by the '%s' strategy.", wt_strategy
);
946 finish(head
, result_commit
, buf
.buf
);
947 strbuf_release(&buf
);
952 static int suggest_conflicts(int renormalizing
)
954 const char *filename
;
958 filename
= git_path("MERGE_MSG");
959 fp
= fopen(filename
, "a");
961 die_errno(_("Could not open '%s' for writing"), filename
);
962 fprintf(fp
, "\nConflicts:\n");
963 for (pos
= 0; pos
< active_nr
; pos
++) {
964 struct cache_entry
*ce
= active_cache
[pos
];
967 fprintf(fp
, "\t%s\n", ce
->name
);
968 while (pos
+ 1 < active_nr
&&
970 active_cache
[pos
+ 1]->name
))
975 rerere(allow_rerere_auto
);
976 printf(_("Automatic merge failed; "
977 "fix conflicts and then commit the result.\n"));
981 static struct commit
*is_old_style_invocation(int argc
, const char **argv
,
982 const unsigned char *head
)
984 struct commit
*second_token
= NULL
;
986 unsigned char second_sha1
[20];
988 if (get_sha1(argv
[1], second_sha1
))
990 second_token
= lookup_commit_reference_gently(second_sha1
, 0);
992 die(_("'%s' is not a commit"), argv
[1]);
993 if (hashcmp(second_token
->object
.sha1
, head
))
999 static int evaluate_result(void)
1002 struct rev_info rev
;
1004 /* Check how many files differ. */
1005 init_revisions(&rev
, "");
1006 setup_revisions(0, NULL
, &rev
, NULL
);
1007 rev
.diffopt
.output_format
|=
1008 DIFF_FORMAT_CALLBACK
;
1009 rev
.diffopt
.format_callback
= count_diff_files
;
1010 rev
.diffopt
.format_callback_data
= &cnt
;
1011 run_diff_files(&rev
, 0);
1014 * Check how many unmerged entries are
1017 cnt
+= count_unmerged_entries();
1023 * Pretend as if the user told us to merge with the tracking
1024 * branch we have for the upstream of the current branch
1026 static int setup_with_upstream(const char ***argv
)
1028 struct branch
*branch
= branch_get(NULL
);
1033 die(_("No current branch."));
1034 if (!branch
->remote
)
1035 die(_("No remote for the current branch."));
1036 if (!branch
->merge_nr
)
1037 die(_("No default upstream defined for the current branch."));
1039 args
= xcalloc(branch
->merge_nr
+ 1, sizeof(char *));
1040 for (i
= 0; i
< branch
->merge_nr
; i
++) {
1041 if (!branch
->merge
[i
]->dst
)
1042 die(_("No remote tracking branch for %s from %s"),
1043 branch
->merge
[i
]->src
, branch
->remote_name
);
1044 args
[i
] = branch
->merge
[i
]->dst
;
1051 static void write_merge_state(void)
1053 const char *filename
;
1055 struct commit_list
*j
;
1056 struct strbuf buf
= STRBUF_INIT
;
1058 for (j
= remoteheads
; j
; j
= j
->next
) {
1059 unsigned const char *sha1
;
1060 struct commit
*c
= j
->item
;
1061 if (c
->util
&& merge_remote_util(c
)->obj
) {
1062 sha1
= merge_remote_util(c
)->obj
->sha1
;
1064 sha1
= c
->object
.sha1
;
1066 strbuf_addf(&buf
, "%s\n", sha1_to_hex(sha1
));
1068 filename
= git_path("MERGE_HEAD");
1069 fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
1071 die_errno(_("Could not open '%s' for writing"), filename
);
1072 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1073 die_errno(_("Could not write to '%s'"), filename
);
1075 strbuf_addch(&merge_msg
, '\n');
1076 write_merge_msg(&merge_msg
);
1078 filename
= git_path("MERGE_MODE");
1079 fd
= open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
1081 die_errno(_("Could not open '%s' for writing"), filename
);
1083 if (!allow_fast_forward
)
1084 strbuf_addf(&buf
, "no-ff");
1085 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1086 die_errno(_("Could not write to '%s'"), filename
);
1090 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
1092 unsigned char result_tree
[20];
1093 unsigned char stash
[20];
1094 unsigned char head_sha1
[20];
1095 struct commit
*head_commit
;
1096 struct strbuf buf
= STRBUF_INIT
;
1097 const char *head_arg
;
1098 int flag
, i
, ret
= 0;
1099 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
1100 struct commit_list
*common
= NULL
;
1101 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
1102 struct commit_list
**remotes
= &remoteheads
;
1103 void *branch_to_free
;
1105 if (argc
== 2 && !strcmp(argv
[1], "-h"))
1106 usage_with_options(builtin_merge_usage
, builtin_merge_options
);
1109 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1112 branch
= branch_to_free
= resolve_refdup("HEAD", head_sha1
, 0, &flag
);
1113 if (branch
&& !prefixcmp(branch
, "refs/heads/"))
1115 if (!branch
|| is_null_sha1(head_sha1
))
1118 head_commit
= lookup_commit_or_die(head_sha1
, "HEAD");
1120 git_config(git_merge_config
, NULL
);
1122 if (branch_mergeoptions
)
1123 parse_branch_merge_options(branch_mergeoptions
);
1124 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
1125 builtin_merge_usage
, 0);
1126 if (shortlog_len
< 0)
1127 shortlog_len
= (merge_log_config
> 0) ? merge_log_config
: 0;
1129 if (verbosity
< 0 && show_progress
== -1)
1132 if (abort_current_merge
) {
1134 const char *nargv
[] = {"reset", "--merge", NULL
};
1136 if (!file_exists(git_path("MERGE_HEAD")))
1137 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1139 /* Invoke 'git reset --merge' */
1140 ret
= cmd_reset(nargc
, nargv
, prefix
);
1144 if (read_cache_unmerged())
1145 die_resolve_conflict("merge");
1147 if (file_exists(git_path("MERGE_HEAD"))) {
1149 * There is no unmerged entry, don't advise 'git
1150 * add/rm <file>', just 'git commit'.
1152 if (advice_resolve_conflict
)
1153 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1154 "Please, commit your changes before you can merge."));
1156 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1158 if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
1159 if (advice_resolve_conflict
)
1160 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1161 "Please, commit your changes before you can merge."));
1163 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1165 resolve_undo_clear();
1171 if (!allow_fast_forward
)
1172 die(_("You cannot combine --squash with --no-ff."));
1176 if (!allow_fast_forward
&& fast_forward_only
)
1177 die(_("You cannot combine --no-ff with --ff-only."));
1179 if (!abort_current_merge
) {
1181 if (default_to_upstream
)
1182 argc
= setup_with_upstream(&argv
);
1184 die(_("No commit specified and merge.defaultToUpstream not set."));
1185 } else if (argc
== 1 && !strcmp(argv
[0], "-"))
1189 usage_with_options(builtin_merge_usage
,
1190 builtin_merge_options
);
1193 * This could be traditional "merge <msg> HEAD <commit>..." and
1194 * the way we can tell it is to see if the second token is HEAD,
1195 * but some people might have misused the interface and used a
1196 * committish that is the same as HEAD there instead.
1197 * Traditional format never would have "-m" so it is an
1198 * additional safety measure to check for it.
1201 if (!have_message
&& head_commit
&&
1202 is_old_style_invocation(argc
, argv
, head_commit
->object
.sha1
)) {
1203 strbuf_addstr(&merge_msg
, argv
[0]);
1207 } else if (!head_commit
) {
1208 struct commit
*remote_head
;
1210 * If the merged head is a valid one there is no reason
1211 * to forbid "git merge" into a branch yet to be born.
1212 * We do the same for "git pull".
1215 die(_("Can merge only exactly one commit into "
1218 die(_("Squash commit into empty head not supported yet"));
1219 if (!allow_fast_forward
)
1220 die(_("Non-fast-forward commit does not make sense into "
1222 remote_head
= get_merge_parent(argv
[0]);
1224 die(_("%s - not something we can merge"), argv
[0]);
1225 read_empty(remote_head
->object
.sha1
, 0);
1226 update_ref("initial pull", "HEAD", remote_head
->object
.sha1
,
1227 NULL
, 0, DIE_ON_ERR
);
1230 struct strbuf merge_names
= STRBUF_INIT
;
1232 /* We are invoked directly as the first-class UI. */
1236 * All the rest are the commits being merged; prepare
1237 * the standard merge summary message to be appended
1238 * to the given message.
1240 for (i
= 0; i
< argc
; i
++)
1241 merge_name(argv
[i
], &merge_names
);
1243 if (!have_message
|| shortlog_len
) {
1244 struct fmt_merge_msg_opts opts
;
1245 memset(&opts
, 0, sizeof(opts
));
1246 opts
.add_title
= !have_message
;
1247 opts
.shortlog_len
= shortlog_len
;
1249 fmt_merge_msg(&merge_names
, &merge_msg
, &opts
);
1251 strbuf_setlen(&merge_msg
, merge_msg
.len
- 1);
1255 if (!head_commit
|| !argc
)
1256 usage_with_options(builtin_merge_usage
,
1257 builtin_merge_options
);
1259 strbuf_addstr(&buf
, "merge");
1260 for (i
= 0; i
< argc
; i
++)
1261 strbuf_addf(&buf
, " %s", argv
[i
]);
1262 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
1265 for (i
= 0; i
< argc
; i
++) {
1266 struct commit
*commit
= get_merge_parent(argv
[i
]);
1268 die(_("%s - not something we can merge"), argv
[i
]);
1269 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1270 strbuf_addf(&buf
, "GITHEAD_%s",
1271 sha1_to_hex(commit
->object
.sha1
));
1272 setenv(buf
.buf
, argv
[i
], 1);
1274 if (merge_remote_util(commit
) &&
1275 merge_remote_util(commit
)->obj
&&
1276 merge_remote_util(commit
)->obj
->type
== OBJ_TAG
) {
1278 allow_fast_forward
= 0;
1282 if (!use_strategies
) {
1283 if (!remoteheads
->next
)
1284 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
1286 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
1289 for (i
= 0; i
< use_strategies_nr
; i
++) {
1290 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
1291 allow_fast_forward
= 0;
1292 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
1296 if (!remoteheads
->next
)
1297 common
= get_merge_bases(head_commit
, remoteheads
->item
, 1);
1299 struct commit_list
*list
= remoteheads
;
1300 commit_list_insert(head_commit
, &list
);
1301 common
= get_octopus_merge_bases(list
);
1305 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head_commit
->object
.sha1
,
1306 NULL
, 0, DIE_ON_ERR
);
1309 ; /* No common ancestors found. We need a real merge. */
1310 else if (!remoteheads
->next
&& !common
->next
&&
1311 common
->item
== remoteheads
->item
) {
1313 * If head can reach all the merge then we are up to date.
1314 * but first the most common case of merging one remote.
1316 finish_up_to_date("Already up-to-date.");
1318 } else if (allow_fast_forward
&& !remoteheads
->next
&&
1320 !hashcmp(common
->item
->object
.sha1
, head_commit
->object
.sha1
)) {
1321 /* Again the most common case of merging one remote. */
1322 struct strbuf msg
= STRBUF_INIT
;
1323 struct commit
*commit
;
1326 strcpy(hex
, find_unique_abbrev(head_commit
->object
.sha1
, DEFAULT_ABBREV
));
1329 printf(_("Updating %s..%s\n"),
1331 find_unique_abbrev(remoteheads
->item
->object
.sha1
,
1333 strbuf_addstr(&msg
, "Fast-forward");
1336 " (no commit created; -m option ignored)");
1337 commit
= remoteheads
->item
;
1343 if (checkout_fast_forward(head_commit
->object
.sha1
,
1344 commit
->object
.sha1
)) {
1349 finish(head_commit
, commit
->object
.sha1
, msg
.buf
);
1352 } else if (!remoteheads
->next
&& common
->next
)
1355 * We are not doing octopus and not fast-forward. Need
1358 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1360 * We are not doing octopus, not fast-forward, and have
1363 refresh_cache(REFRESH_QUIET
);
1364 if (allow_trivial
&& !fast_forward_only
) {
1365 /* See if it is really trivial. */
1366 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1367 printf(_("Trying really trivial in-index merge...\n"));
1368 if (!read_tree_trivial(common
->item
->object
.sha1
,
1369 head_commit
->object
.sha1
,
1370 remoteheads
->item
->object
.sha1
)) {
1371 ret
= merge_trivial(head_commit
);
1374 printf(_("Nope.\n"));
1378 * An octopus. If we can reach all the remote we are up
1382 struct commit_list
*j
;
1384 for (j
= remoteheads
; j
; j
= j
->next
) {
1385 struct commit_list
*common_one
;
1388 * Here we *have* to calculate the individual
1389 * merge_bases again, otherwise "git merge HEAD^
1390 * HEAD^^" would be missed.
1392 common_one
= get_merge_bases(head_commit
, j
->item
, 1);
1393 if (hashcmp(common_one
->item
->object
.sha1
,
1394 j
->item
->object
.sha1
)) {
1400 finish_up_to_date("Already up-to-date. Yeeah!");
1405 if (fast_forward_only
)
1406 die(_("Not possible to fast-forward, aborting."));
1408 /* We are going to make a new commit. */
1409 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1412 * At this point, we need a real merge. No matter what strategy
1413 * we use, it would operate on the index, possibly affecting the
1414 * working tree, and when resolved cleanly, have the desired
1415 * tree in the index -- this means that the index must be in
1416 * sync with the head commit. The strategies are responsible
1419 if (use_strategies_nr
== 1 ||
1421 * Stash away the local changes so that we can try more than one.
1424 hashcpy(stash
, null_sha1
);
1426 for (i
= 0; i
< use_strategies_nr
; i
++) {
1429 printf(_("Rewinding the tree to pristine...\n"));
1430 restore_state(head_commit
->object
.sha1
, stash
);
1432 if (use_strategies_nr
!= 1)
1433 printf(_("Trying merge strategy %s...\n"),
1434 use_strategies
[i
]->name
);
1436 * Remember which strategy left the state in the working
1439 wt_strategy
= use_strategies
[i
]->name
;
1441 ret
= try_merge_strategy(use_strategies
[i
]->name
,
1442 common
, head_commit
, head_arg
);
1443 if (!option_commit
&& !ret
) {
1446 * This is necessary here just to avoid writing
1447 * the tree, but later we will *not* exit with
1448 * status code 1 because merge_was_ok is set.
1455 * The backend exits with 1 when conflicts are
1456 * left to be resolved, with 2 when it does not
1457 * handle the given merge at all.
1460 int cnt
= evaluate_result();
1462 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1463 best_strategy
= use_strategies
[i
]->name
;
1473 /* Automerge succeeded. */
1474 write_tree_trivial(result_tree
);
1475 automerge_was_ok
= 1;
1480 * If we have a resulting tree, that means the strategy module
1481 * auto resolved the merge cleanly.
1483 if (automerge_was_ok
) {
1484 ret
= finish_automerge(head_commit
, common
, result_tree
,
1490 * Pick the result from the best strategy and have the user fix
1493 if (!best_strategy
) {
1494 restore_state(head_commit
->object
.sha1
, stash
);
1495 if (use_strategies_nr
> 1)
1497 _("No merge strategy handled the merge.\n"));
1499 fprintf(stderr
, _("Merge with strategy %s failed.\n"),
1500 use_strategies
[0]->name
);
1503 } else if (best_strategy
== wt_strategy
)
1504 ; /* We already have its result in the working tree. */
1506 printf(_("Rewinding the tree to pristine...\n"));
1507 restore_state(head_commit
->object
.sha1
, stash
);
1508 printf(_("Using the %s to prepare resolving by hand.\n"),
1510 try_merge_strategy(best_strategy
, common
, head_commit
, head_arg
);
1514 finish(head_commit
, NULL
, NULL
);
1516 write_merge_state();
1519 fprintf(stderr
, _("Automatic merge went well; "
1520 "stopped before committing as requested\n"));
1522 ret
= suggest_conflicts(option_renormalize
);
1525 free(branch_to_free
);