4 * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
6 * Based on git-merge.sh by Junio C Hamano.
10 #include "parse-options.h"
12 #include "run-command.h"
18 #include "unpack-trees.h"
19 #include "cache-tree.h"
26 #include "merge-recursive.h"
27 #include "resolve-undo.h"
30 #define DEFAULT_TWOHEAD (1<<0)
31 #define DEFAULT_OCTOPUS (1<<1)
32 #define NO_FAST_FORWARD (1<<2)
33 #define NO_TRIVIAL (1<<3)
40 static const char * const builtin_merge_usage
[] = {
41 "git merge [options] [<commit>...]",
42 "git merge [options] <msg> HEAD <commit>",
47 static int show_diffstat
= 1, shortlog_len
, squash
;
48 static int option_commit
= 1, allow_fast_forward
= 1;
49 static int fast_forward_only
;
50 static int allow_trivial
= 1, have_message
;
51 static struct strbuf merge_msg
;
52 static struct commit_list
*remoteheads
;
53 static unsigned char head
[20], stash
[20];
54 static struct strategy
**use_strategies
;
55 static size_t use_strategies_nr
, use_strategies_alloc
;
56 static const char **xopts
;
57 static size_t xopts_nr
, xopts_alloc
;
58 static const char *branch
;
59 static char *branch_mergeoptions
;
60 static int option_renormalize
;
62 static int allow_rerere_auto
;
63 static int abort_current_merge
;
64 static int show_progress
= -1;
65 static int default_to_upstream
;
67 static struct strategy all_strategy
[] = {
68 { "recursive", DEFAULT_TWOHEAD
| NO_TRIVIAL
},
69 { "octopus", DEFAULT_OCTOPUS
},
71 { "ours", NO_FAST_FORWARD
| NO_TRIVIAL
},
72 { "subtree", NO_FAST_FORWARD
| NO_TRIVIAL
},
75 static const char *pull_twohead
, *pull_octopus
;
77 static int option_parse_message(const struct option
*opt
,
78 const char *arg
, int unset
)
80 struct strbuf
*buf
= opt
->value
;
83 strbuf_setlen(buf
, 0);
85 strbuf_addf(buf
, "%s%s", buf
->len
? "\n\n" : "", arg
);
88 return error(_("switch `m' requires a value"));
92 static struct strategy
*get_strategy(const char *name
)
96 static struct cmdnames main_cmds
, other_cmds
;
102 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
103 if (!strcmp(name
, all_strategy
[i
].name
))
104 return &all_strategy
[i
];
107 struct cmdnames not_strategies
;
110 memset(¬_strategies
, 0, sizeof(struct cmdnames
));
111 load_command_list("git-merge-", &main_cmds
, &other_cmds
);
112 for (i
= 0; i
< main_cmds
.cnt
; i
++) {
114 struct cmdname
*ent
= main_cmds
.names
[i
];
115 for (j
= 0; j
< ARRAY_SIZE(all_strategy
); j
++)
116 if (!strncmp(ent
->name
, all_strategy
[j
].name
, ent
->len
)
117 && !all_strategy
[j
].name
[ent
->len
])
120 add_cmdname(¬_strategies
, ent
->name
, ent
->len
);
122 exclude_cmds(&main_cmds
, ¬_strategies
);
124 if (!is_in_cmdlist(&main_cmds
, name
) && !is_in_cmdlist(&other_cmds
, name
)) {
125 fprintf(stderr
, _("Could not find merge strategy '%s'.\n"), name
);
126 fprintf(stderr
, _("Available strategies are:"));
127 for (i
= 0; i
< main_cmds
.cnt
; i
++)
128 fprintf(stderr
, " %s", main_cmds
.names
[i
]->name
);
129 fprintf(stderr
, ".\n");
130 if (other_cmds
.cnt
) {
131 fprintf(stderr
, _("Available custom strategies are:"));
132 for (i
= 0; i
< other_cmds
.cnt
; i
++)
133 fprintf(stderr
, " %s", other_cmds
.names
[i
]->name
);
134 fprintf(stderr
, ".\n");
139 ret
= xcalloc(1, sizeof(struct strategy
));
140 ret
->name
= xstrdup(name
);
141 ret
->attr
= NO_TRIVIAL
;
145 static void append_strategy(struct strategy
*s
)
147 ALLOC_GROW(use_strategies
, use_strategies_nr
+ 1, use_strategies_alloc
);
148 use_strategies
[use_strategies_nr
++] = s
;
151 static int option_parse_strategy(const struct option
*opt
,
152 const char *name
, int unset
)
157 append_strategy(get_strategy(name
));
161 static int option_parse_x(const struct option
*opt
,
162 const char *arg
, int unset
)
167 ALLOC_GROW(xopts
, xopts_nr
+ 1, xopts_alloc
);
168 xopts
[xopts_nr
++] = xstrdup(arg
);
172 static int option_parse_n(const struct option
*opt
,
173 const char *arg
, int unset
)
175 show_diffstat
= unset
;
179 static struct option builtin_merge_options
[] = {
180 { OPTION_CALLBACK
, 'n', NULL
, NULL
, NULL
,
181 "do not show a diffstat at the end of the merge",
182 PARSE_OPT_NOARG
, option_parse_n
},
183 OPT_BOOLEAN(0, "stat", &show_diffstat
,
184 "show a diffstat at the end of the merge"),
185 OPT_BOOLEAN(0, "summary", &show_diffstat
, "(synonym to --stat)"),
186 { OPTION_INTEGER
, 0, "log", &shortlog_len
, "n",
187 "add (at most <n>) entries from shortlog to merge commit message",
188 PARSE_OPT_OPTARG
, NULL
, DEFAULT_MERGE_LOG_LEN
},
189 OPT_BOOLEAN(0, "squash", &squash
,
190 "create a single commit instead of doing a merge"),
191 OPT_BOOLEAN(0, "commit", &option_commit
,
192 "perform a commit if the merge succeeds (default)"),
193 OPT_BOOLEAN(0, "ff", &allow_fast_forward
,
194 "allow fast-forward (default)"),
195 OPT_BOOLEAN(0, "ff-only", &fast_forward_only
,
196 "abort if fast-forward is not possible"),
197 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto
),
198 OPT_CALLBACK('s', "strategy", &use_strategies
, "strategy",
199 "merge strategy to use", option_parse_strategy
),
200 OPT_CALLBACK('X', "strategy-option", &xopts
, "option=value",
201 "option for selected merge strategy", option_parse_x
),
202 OPT_CALLBACK('m', "message", &merge_msg
, "message",
203 "merge commit message (for a non-fast-forward merge)",
204 option_parse_message
),
205 OPT__VERBOSITY(&verbosity
),
206 OPT_BOOLEAN(0, "abort", &abort_current_merge
,
207 "abort the current in-progress merge"),
208 OPT_SET_INT(0, "progress", &show_progress
, "force progress reporting", 1),
212 /* Cleans up metadata that is uninteresting after a succeeded merge. */
213 static void drop_save(void)
215 unlink(git_path("MERGE_HEAD"));
216 unlink(git_path("MERGE_MSG"));
217 unlink(git_path("MERGE_MODE"));
220 static void save_state(void)
223 struct child_process cp
;
224 struct strbuf buffer
= STRBUF_INIT
;
225 const char *argv
[] = {"stash", "create", NULL
};
227 memset(&cp
, 0, sizeof(cp
));
232 if (start_command(&cp
))
233 die(_("could not run stash."));
234 len
= strbuf_read(&buffer
, cp
.out
, 1024);
237 if (finish_command(&cp
) || len
< 0)
238 die(_("stash failed"));
241 strbuf_setlen(&buffer
, buffer
.len
-1);
242 if (get_sha1(buffer
.buf
, stash
))
243 die(_("not a valid object: %s"), buffer
.buf
);
246 static void read_empty(unsigned const char *sha1
, int verbose
)
251 args
[i
++] = "read-tree";
256 args
[i
++] = EMPTY_TREE_SHA1_HEX
;
257 args
[i
++] = sha1_to_hex(sha1
);
260 if (run_command_v_opt(args
, RUN_GIT_CMD
))
261 die(_("read-tree failed"));
264 static void reset_hard(unsigned const char *sha1
, int verbose
)
269 args
[i
++] = "read-tree";
272 args
[i
++] = "--reset";
274 args
[i
++] = sha1_to_hex(sha1
);
277 if (run_command_v_opt(args
, RUN_GIT_CMD
))
278 die(_("read-tree failed"));
281 static void restore_state(void)
283 struct strbuf sb
= STRBUF_INIT
;
284 const char *args
[] = { "stash", "apply", NULL
, NULL
};
286 if (is_null_sha1(stash
))
291 args
[2] = sha1_to_hex(stash
);
294 * It is OK to ignore error here, for example when there was
295 * nothing to restore.
297 run_command_v_opt(args
, RUN_GIT_CMD
);
300 refresh_cache(REFRESH_QUIET
);
303 /* This is called when no merge was necessary. */
304 static void finish_up_to_date(const char *msg
)
307 printf("%s%s\n", squash
? _(" (nothing to squash)") : "", msg
);
311 static void squash_message(void)
314 struct commit
*commit
;
315 struct strbuf out
= STRBUF_INIT
;
316 struct commit_list
*j
;
318 struct pretty_print_context ctx
= {0};
320 printf(_("Squash commit -- not updating HEAD\n"));
321 fd
= open(git_path("SQUASH_MSG"), O_WRONLY
| O_CREAT
, 0666);
323 die_errno(_("Could not write to '%s'"), git_path("SQUASH_MSG"));
325 init_revisions(&rev
, NULL
);
326 rev
.ignore_merges
= 1;
327 rev
.commit_format
= CMIT_FMT_MEDIUM
;
329 commit
= lookup_commit(head
);
330 commit
->object
.flags
|= UNINTERESTING
;
331 add_pending_object(&rev
, &commit
->object
, NULL
);
333 for (j
= remoteheads
; j
; j
= j
->next
)
334 add_pending_object(&rev
, &j
->item
->object
, NULL
);
336 setup_revisions(0, NULL
, &rev
, NULL
);
337 if (prepare_revision_walk(&rev
))
338 die(_("revision walk setup failed"));
340 ctx
.abbrev
= rev
.abbrev
;
341 ctx
.date_mode
= rev
.date_mode
;
342 ctx
.fmt
= rev
.commit_format
;
344 strbuf_addstr(&out
, "Squashed commit of the following:\n");
345 while ((commit
= get_revision(&rev
)) != NULL
) {
346 strbuf_addch(&out
, '\n');
347 strbuf_addf(&out
, "commit %s\n",
348 sha1_to_hex(commit
->object
.sha1
));
349 pretty_print_commit(&ctx
, commit
, &out
);
351 if (write(fd
, out
.buf
, out
.len
) < 0)
352 die_errno(_("Writing SQUASH_MSG"));
354 die_errno(_("Finishing SQUASH_MSG"));
355 strbuf_release(&out
);
358 static void finish(const unsigned char *new_head
, const char *msg
)
360 struct strbuf reflog_message
= STRBUF_INIT
;
363 strbuf_addstr(&reflog_message
, getenv("GIT_REFLOG_ACTION"));
367 strbuf_addf(&reflog_message
, "%s: %s",
368 getenv("GIT_REFLOG_ACTION"), msg
);
373 if (verbosity
>= 0 && !merge_msg
.len
)
374 printf(_("No merge message -- not updating HEAD\n"));
376 const char *argv_gc_auto
[] = { "gc", "--auto", NULL
};
377 update_ref(reflog_message
.buf
, "HEAD",
381 * We ignore errors in 'gc --auto', since the
382 * user should see them.
384 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
387 if (new_head
&& show_diffstat
) {
388 struct diff_options opts
;
390 opts
.output_format
|=
391 DIFF_FORMAT_SUMMARY
| DIFF_FORMAT_DIFFSTAT
;
392 opts
.detect_rename
= DIFF_DETECT_RENAME
;
393 if (diff_use_color_default
> 0)
394 DIFF_OPT_SET(&opts
, COLOR_DIFF
);
395 if (diff_setup_done(&opts
) < 0)
396 die(_("diff_setup_done failed"));
397 diff_tree_sha1(head
, new_head
, "", &opts
);
402 /* Run a post-merge hook */
403 run_hook(NULL
, "post-merge", squash
? "1" : "0", NULL
);
405 strbuf_release(&reflog_message
);
408 /* Get the name for the merge commit's message. */
409 static void merge_name(const char *remote
, struct strbuf
*msg
)
411 struct object
*remote_head
;
412 unsigned char branch_head
[20], buf_sha
[20];
413 struct strbuf buf
= STRBUF_INIT
;
414 struct strbuf bname
= STRBUF_INIT
;
419 strbuf_branchname(&bname
, remote
);
422 memset(branch_head
, 0, sizeof(branch_head
));
423 remote_head
= peel_to_type(remote
, 0, NULL
, OBJ_COMMIT
);
425 die(_("'%s' does not point to a commit"), remote
);
427 if (dwim_ref(remote
, strlen(remote
), branch_head
, &found_ref
) > 0) {
428 if (!prefixcmp(found_ref
, "refs/heads/")) {
429 strbuf_addf(msg
, "%s\t\tbranch '%s' of .\n",
430 sha1_to_hex(branch_head
), remote
);
433 if (!prefixcmp(found_ref
, "refs/remotes/")) {
434 strbuf_addf(msg
, "%s\t\tremote-tracking branch '%s' of .\n",
435 sha1_to_hex(branch_head
), remote
);
440 /* See if remote matches <name>^^^.. or <name>~<number> */
441 for (len
= 0, ptr
= remote
+ strlen(remote
);
442 remote
< ptr
&& ptr
[-1] == '^';
449 ptr
= strrchr(remote
, '~');
451 int seen_nonzero
= 0;
454 while (*++ptr
&& isdigit(*ptr
)) {
455 seen_nonzero
|= (*ptr
!= '0');
459 len
= 0; /* not ...~<number> */
460 else if (seen_nonzero
)
463 early
= 1; /* "name~" is "name~1"! */
467 struct strbuf truname
= STRBUF_INIT
;
468 strbuf_addstr(&truname
, "refs/heads/");
469 strbuf_addstr(&truname
, remote
);
470 strbuf_setlen(&truname
, truname
.len
- len
);
471 if (resolve_ref(truname
.buf
, buf_sha
, 1, NULL
)) {
473 "%s\t\tbranch '%s'%s of .\n",
474 sha1_to_hex(remote_head
->sha1
),
476 (early
? " (early part)" : ""));
477 strbuf_release(&truname
);
482 if (!strcmp(remote
, "FETCH_HEAD") &&
483 !access(git_path("FETCH_HEAD"), R_OK
)) {
485 struct strbuf line
= STRBUF_INIT
;
488 fp
= fopen(git_path("FETCH_HEAD"), "r");
490 die_errno(_("could not open '%s' for reading"),
491 git_path("FETCH_HEAD"));
492 strbuf_getline(&line
, fp
, '\n');
494 ptr
= strstr(line
.buf
, "\tnot-for-merge\t");
496 strbuf_remove(&line
, ptr
-line
.buf
+1, 13);
497 strbuf_addbuf(msg
, &line
);
498 strbuf_release(&line
);
501 strbuf_addf(msg
, "%s\t\tcommit '%s'\n",
502 sha1_to_hex(remote_head
->sha1
), remote
);
504 strbuf_release(&buf
);
505 strbuf_release(&bname
);
508 static void parse_branch_merge_options(char *bmo
)
515 argc
= split_cmdline(bmo
, &argv
);
517 die(_("Bad branch.%s.mergeoptions string: %s"), branch
,
518 split_cmdline_strerror(argc
));
519 argv
= xrealloc(argv
, sizeof(*argv
) * (argc
+ 2));
520 memmove(argv
+ 1, argv
, sizeof(*argv
) * (argc
+ 1));
522 argv
[0] = "branch.*.mergeoptions";
523 parse_options(argc
, argv
, NULL
, builtin_merge_options
,
524 builtin_merge_usage
, 0);
528 static int git_merge_config(const char *k
, const char *v
, void *cb
)
530 if (branch
&& !prefixcmp(k
, "branch.") &&
531 !prefixcmp(k
+ 7, branch
) &&
532 !strcmp(k
+ 7 + strlen(branch
), ".mergeoptions")) {
533 free(branch_mergeoptions
);
534 branch_mergeoptions
= xstrdup(v
);
538 if (!strcmp(k
, "merge.diffstat") || !strcmp(k
, "merge.stat"))
539 show_diffstat
= git_config_bool(k
, v
);
540 else if (!strcmp(k
, "pull.twohead"))
541 return git_config_string(&pull_twohead
, k
, v
);
542 else if (!strcmp(k
, "pull.octopus"))
543 return git_config_string(&pull_octopus
, k
, v
);
544 else if (!strcmp(k
, "merge.renormalize"))
545 option_renormalize
= git_config_bool(k
, v
);
546 else if (!strcmp(k
, "merge.log") || !strcmp(k
, "merge.summary")) {
548 shortlog_len
= git_config_bool_or_int(k
, v
, &is_bool
);
549 if (!is_bool
&& shortlog_len
< 0)
550 return error(_("%s: negative length %s"), k
, v
);
551 if (is_bool
&& shortlog_len
)
552 shortlog_len
= DEFAULT_MERGE_LOG_LEN
;
554 } else if (!strcmp(k
, "merge.ff")) {
555 int boolval
= git_config_maybe_bool(k
, v
);
557 allow_fast_forward
= boolval
;
558 } else if (v
&& !strcmp(v
, "only")) {
559 allow_fast_forward
= 1;
560 fast_forward_only
= 1;
561 } /* do not barf on values from future versions of git */
563 } else if (!strcmp(k
, "merge.defaulttoupstream")) {
564 default_to_upstream
= git_config_bool(k
, v
);
567 return git_diff_ui_config(k
, v
, cb
);
570 static int read_tree_trivial(unsigned char *common
, unsigned char *head
,
574 struct tree
*trees
[MAX_UNPACK_TREES
];
575 struct tree_desc t
[MAX_UNPACK_TREES
];
576 struct unpack_trees_options opts
;
578 memset(&opts
, 0, sizeof(opts
));
580 opts
.src_index
= &the_index
;
581 opts
.dst_index
= &the_index
;
583 opts
.verbose_update
= 1;
584 opts
.trivial_merges_only
= 1;
586 trees
[nr_trees
] = parse_tree_indirect(common
);
587 if (!trees
[nr_trees
++])
589 trees
[nr_trees
] = parse_tree_indirect(head
);
590 if (!trees
[nr_trees
++])
592 trees
[nr_trees
] = parse_tree_indirect(one
);
593 if (!trees
[nr_trees
++])
595 opts
.fn
= threeway_merge
;
596 cache_tree_free(&active_cache_tree
);
597 for (i
= 0; i
< nr_trees
; i
++) {
598 parse_tree(trees
[i
]);
599 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
601 if (unpack_trees(nr_trees
, t
, &opts
))
606 static void write_tree_trivial(unsigned char *sha1
)
608 if (write_cache_as_tree(sha1
, 0, NULL
))
609 die(_("git write-tree failed to write a tree"));
612 static const char *merge_argument(struct commit
*commit
)
615 return sha1_to_hex(commit
->object
.sha1
);
617 return EMPTY_TREE_SHA1_HEX
;
620 int try_merge_command(const char *strategy
, size_t xopts_nr
,
621 const char **xopts
, struct commit_list
*common
,
622 const char *head_arg
, struct commit_list
*remotes
)
625 int i
= 0, x
= 0, ret
;
626 struct commit_list
*j
;
627 struct strbuf buf
= STRBUF_INIT
;
629 args
= xmalloc((4 + xopts_nr
+ commit_list_count(common
) +
630 commit_list_count(remotes
)) * sizeof(char *));
631 strbuf_addf(&buf
, "merge-%s", strategy
);
633 for (x
= 0; x
< xopts_nr
; x
++) {
634 char *s
= xmalloc(strlen(xopts
[x
])+2+1);
636 strcpy(s
+2, xopts
[x
]);
639 for (j
= common
; j
; j
= j
->next
)
640 args
[i
++] = xstrdup(merge_argument(j
->item
));
642 args
[i
++] = head_arg
;
643 for (j
= remotes
; j
; j
= j
->next
)
644 args
[i
++] = xstrdup(merge_argument(j
->item
));
646 ret
= run_command_v_opt(args
, RUN_GIT_CMD
);
647 strbuf_release(&buf
);
649 for (x
= 0; x
< xopts_nr
; x
++)
650 free((void *)args
[i
++]);
651 for (j
= common
; j
; j
= j
->next
)
652 free((void *)args
[i
++]);
654 for (j
= remotes
; j
; j
= j
->next
)
655 free((void *)args
[i
++]);
658 if (read_cache() < 0)
659 die(_("failed to read the cache"));
660 resolve_undo_clear();
665 static int try_merge_strategy(const char *strategy
, struct commit_list
*common
,
666 const char *head_arg
)
669 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
671 index_fd
= hold_locked_index(lock
, 1);
672 refresh_cache(REFRESH_QUIET
);
673 if (active_cache_changed
&&
674 (write_cache(index_fd
, active_cache
, active_nr
) ||
675 commit_locked_index(lock
)))
676 return error(_("Unable to write index."));
677 rollback_lock_file(lock
);
679 if (!strcmp(strategy
, "recursive") || !strcmp(strategy
, "subtree")) {
681 struct commit
*result
;
682 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
684 struct commit_list
*reversed
= NULL
;
685 struct merge_options o
;
686 struct commit_list
*j
;
688 if (remoteheads
->next
) {
689 error(_("Not handling anything other than two heads merge."));
693 init_merge_options(&o
);
694 if (!strcmp(strategy
, "subtree"))
695 o
.subtree_shift
= "";
697 o
.renormalize
= option_renormalize
;
698 o
.show_rename_progress
=
699 show_progress
== -1 ? isatty(2) : show_progress
;
701 for (x
= 0; x
< xopts_nr
; x
++)
702 if (parse_merge_opt(&o
, xopts
[x
]))
703 die(_("Unknown option for merge-recursive: -X%s"), xopts
[x
]);
705 o
.branch1
= head_arg
;
706 o
.branch2
= remoteheads
->item
->util
;
708 for (j
= common
; j
; j
= j
->next
)
709 commit_list_insert(j
->item
, &reversed
);
711 index_fd
= hold_locked_index(lock
, 1);
712 clean
= merge_recursive(&o
, lookup_commit(head
),
713 remoteheads
->item
, reversed
, &result
);
714 if (active_cache_changed
&&
715 (write_cache(index_fd
, active_cache
, active_nr
) ||
716 commit_locked_index(lock
)))
717 die (_("unable to write %s"), get_index_file());
718 rollback_lock_file(lock
);
719 return clean
? 0 : 1;
721 return try_merge_command(strategy
, xopts_nr
, xopts
,
722 common
, head_arg
, remoteheads
);
726 static void count_diff_files(struct diff_queue_struct
*q
,
727 struct diff_options
*opt
, void *data
)
734 static int count_unmerged_entries(void)
738 for (i
= 0; i
< active_nr
; i
++)
739 if (ce_stage(active_cache
[i
]))
745 int checkout_fast_forward(const unsigned char *head
, const unsigned char *remote
)
747 struct tree
*trees
[MAX_UNPACK_TREES
];
748 struct unpack_trees_options opts
;
749 struct tree_desc t
[MAX_UNPACK_TREES
];
750 int i
, fd
, nr_trees
= 0;
751 struct dir_struct dir
;
752 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
754 refresh_cache(REFRESH_QUIET
);
756 fd
= hold_locked_index(lock_file
, 1);
758 memset(&trees
, 0, sizeof(trees
));
759 memset(&opts
, 0, sizeof(opts
));
760 memset(&t
, 0, sizeof(t
));
761 memset(&dir
, 0, sizeof(dir
));
762 dir
.flags
|= DIR_SHOW_IGNORED
;
763 dir
.exclude_per_dir
= ".gitignore";
767 opts
.src_index
= &the_index
;
768 opts
.dst_index
= &the_index
;
770 opts
.verbose_update
= 1;
772 opts
.fn
= twoway_merge
;
773 setup_unpack_trees_porcelain(&opts
, "merge");
775 trees
[nr_trees
] = parse_tree_indirect(head
);
776 if (!trees
[nr_trees
++])
778 trees
[nr_trees
] = parse_tree_indirect(remote
);
779 if (!trees
[nr_trees
++])
781 for (i
= 0; i
< nr_trees
; i
++) {
782 parse_tree(trees
[i
]);
783 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
785 if (unpack_trees(nr_trees
, t
, &opts
))
787 if (write_cache(fd
, active_cache
, active_nr
) ||
788 commit_locked_index(lock_file
))
789 die(_("unable to write new index file"));
793 static void split_merge_strategies(const char *string
, struct strategy
**list
,
801 buf
= xstrdup(string
);
806 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
807 (*list
)[(*nr
)++].name
= xstrdup(q
);
812 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
813 (*list
)[(*nr
)++].name
= xstrdup(q
);
819 static void add_strategies(const char *string
, unsigned attr
)
821 struct strategy
*list
= NULL
;
822 int list_alloc
= 0, list_nr
= 0, i
;
824 memset(&list
, 0, sizeof(list
));
825 split_merge_strategies(string
, &list
, &list_nr
, &list_alloc
);
827 for (i
= 0; i
< list_nr
; i
++)
828 append_strategy(get_strategy(list
[i
].name
));
831 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
832 if (all_strategy
[i
].attr
& attr
)
833 append_strategy(&all_strategy
[i
]);
837 static void write_merge_msg(void)
839 int fd
= open(git_path("MERGE_MSG"), O_WRONLY
| O_CREAT
, 0666);
841 die_errno(_("Could not open '%s' for writing"),
842 git_path("MERGE_MSG"));
843 if (write_in_full(fd
, merge_msg
.buf
, merge_msg
.len
) != merge_msg
.len
)
844 die_errno(_("Could not write to '%s'"), git_path("MERGE_MSG"));
848 static void read_merge_msg(void)
850 strbuf_reset(&merge_msg
);
851 if (strbuf_read_file(&merge_msg
, git_path("MERGE_MSG"), 0) < 0)
852 die_errno(_("Could not read from '%s'"), git_path("MERGE_MSG"));
855 static void run_prepare_commit_msg(void)
858 run_hook(get_index_file(), "prepare-commit-msg",
859 git_path("MERGE_MSG"), "merge", NULL
, NULL
);
863 static int merge_trivial(void)
865 unsigned char result_tree
[20], result_commit
[20];
866 struct commit_list
*parent
= xmalloc(sizeof(*parent
));
868 write_tree_trivial(result_tree
);
869 printf(_("Wonderful.\n"));
870 parent
->item
= lookup_commit(head
);
871 parent
->next
= xmalloc(sizeof(*parent
->next
));
872 parent
->next
->item
= remoteheads
->item
;
873 parent
->next
->next
= NULL
;
874 run_prepare_commit_msg();
875 commit_tree(merge_msg
.buf
, result_tree
, parent
, result_commit
, NULL
);
876 finish(result_commit
, "In-index merge");
881 static int finish_automerge(struct commit_list
*common
,
882 unsigned char *result_tree
,
883 const char *wt_strategy
)
885 struct commit_list
*parents
= NULL
, *j
;
886 struct strbuf buf
= STRBUF_INIT
;
887 unsigned char result_commit
[20];
889 free_commit_list(common
);
890 if (allow_fast_forward
) {
891 parents
= remoteheads
;
892 commit_list_insert(lookup_commit(head
), &parents
);
893 parents
= reduce_heads(parents
);
895 struct commit_list
**pptr
= &parents
;
897 pptr
= &commit_list_insert(lookup_commit(head
),
899 for (j
= remoteheads
; j
; j
= j
->next
)
900 pptr
= &commit_list_insert(j
->item
, pptr
)->next
;
902 free_commit_list(remoteheads
);
903 strbuf_addch(&merge_msg
, '\n');
904 run_prepare_commit_msg();
905 commit_tree(merge_msg
.buf
, result_tree
, parents
, result_commit
, NULL
);
906 strbuf_addf(&buf
, "Merge made by %s.", wt_strategy
);
907 finish(result_commit
, buf
.buf
);
908 strbuf_release(&buf
);
913 static int suggest_conflicts(int renormalizing
)
918 fp
= fopen(git_path("MERGE_MSG"), "a");
920 die_errno(_("Could not open '%s' for writing"),
921 git_path("MERGE_MSG"));
922 fprintf(fp
, "\nConflicts:\n");
923 for (pos
= 0; pos
< active_nr
; pos
++) {
924 struct cache_entry
*ce
= active_cache
[pos
];
927 fprintf(fp
, "\t%s\n", ce
->name
);
928 while (pos
+ 1 < active_nr
&&
930 active_cache
[pos
+ 1]->name
))
935 rerere(allow_rerere_auto
);
936 printf(_("Automatic merge failed; "
937 "fix conflicts and then commit the result.\n"));
941 static struct commit
*is_old_style_invocation(int argc
, const char **argv
)
943 struct commit
*second_token
= NULL
;
945 unsigned char second_sha1
[20];
947 if (get_sha1(argv
[1], second_sha1
))
949 second_token
= lookup_commit_reference_gently(second_sha1
, 0);
951 die(_("'%s' is not a commit"), argv
[1]);
952 if (hashcmp(second_token
->object
.sha1
, head
))
958 static int evaluate_result(void)
963 /* Check how many files differ. */
964 init_revisions(&rev
, "");
965 setup_revisions(0, NULL
, &rev
, NULL
);
966 rev
.diffopt
.output_format
|=
967 DIFF_FORMAT_CALLBACK
;
968 rev
.diffopt
.format_callback
= count_diff_files
;
969 rev
.diffopt
.format_callback_data
= &cnt
;
970 run_diff_files(&rev
, 0);
973 * Check how many unmerged entries are
976 cnt
+= count_unmerged_entries();
982 * Pretend as if the user told us to merge with the tracking
983 * branch we have for the upstream of the current branch
985 static int setup_with_upstream(const char ***argv
)
987 struct branch
*branch
= branch_get(NULL
);
992 die(_("No current branch."));
994 die(_("No remote for the current branch."));
995 if (!branch
->merge_nr
)
996 die(_("No default upstream defined for the current branch."));
998 args
= xcalloc(branch
->merge_nr
+ 1, sizeof(char *));
999 for (i
= 0; i
< branch
->merge_nr
; i
++) {
1000 if (!branch
->merge
[i
]->dst
)
1001 die(_("No remote tracking branch for %s from %s"),
1002 branch
->merge
[i
]->src
, branch
->remote_name
);
1003 args
[i
] = branch
->merge
[i
]->dst
;
1010 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
1012 unsigned char result_tree
[20];
1013 struct strbuf buf
= STRBUF_INIT
;
1014 const char *head_arg
;
1015 int flag
, head_invalid
= 0, i
;
1016 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
1017 struct commit_list
*common
= NULL
;
1018 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
1019 struct commit_list
**remotes
= &remoteheads
;
1021 if (argc
== 2 && !strcmp(argv
[1], "-h"))
1022 usage_with_options(builtin_merge_usage
, builtin_merge_options
);
1025 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1028 branch
= resolve_ref("HEAD", head
, 0, &flag
);
1029 if (branch
&& !prefixcmp(branch
, "refs/heads/"))
1031 if (is_null_sha1(head
))
1034 git_config(git_merge_config
, NULL
);
1037 if (diff_use_color_default
== -1)
1038 diff_use_color_default
= git_use_color_default
;
1040 if (branch_mergeoptions
)
1041 parse_branch_merge_options(branch_mergeoptions
);
1042 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
1043 builtin_merge_usage
, 0);
1045 if (verbosity
< 0 && show_progress
== -1)
1048 if (abort_current_merge
) {
1050 const char *nargv
[] = {"reset", "--merge", NULL
};
1052 if (!file_exists(git_path("MERGE_HEAD")))
1053 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1055 /* Invoke 'git reset --merge' */
1056 return cmd_reset(nargc
, nargv
, prefix
);
1059 if (read_cache_unmerged())
1060 die_resolve_conflict("merge");
1062 if (file_exists(git_path("MERGE_HEAD"))) {
1064 * There is no unmerged entry, don't advise 'git
1065 * add/rm <file>', just 'git commit'.
1067 if (advice_resolve_conflict
)
1068 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1069 "Please, commit your changes before you can merge."));
1071 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1073 if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
1074 if (advice_resolve_conflict
)
1075 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1076 "Please, commit your changes before you can merge."));
1078 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1080 resolve_undo_clear();
1086 if (!allow_fast_forward
)
1087 die(_("You cannot combine --squash with --no-ff."));
1091 if (!allow_fast_forward
&& fast_forward_only
)
1092 die(_("You cannot combine --no-ff with --ff-only."));
1094 if (!abort_current_merge
) {
1095 if (!argc
&& default_to_upstream
)
1096 argc
= setup_with_upstream(&argv
);
1097 else if (argc
== 1 && !strcmp(argv
[0], "-"))
1101 usage_with_options(builtin_merge_usage
,
1102 builtin_merge_options
);
1105 * This could be traditional "merge <msg> HEAD <commit>..." and
1106 * the way we can tell it is to see if the second token is HEAD,
1107 * but some people might have misused the interface and used a
1108 * committish that is the same as HEAD there instead.
1109 * Traditional format never would have "-m" so it is an
1110 * additional safety measure to check for it.
1113 if (!have_message
&& is_old_style_invocation(argc
, argv
)) {
1114 strbuf_addstr(&merge_msg
, argv
[0]);
1118 } else if (head_invalid
) {
1119 struct object
*remote_head
;
1121 * If the merged head is a valid one there is no reason
1122 * to forbid "git merge" into a branch yet to be born.
1123 * We do the same for "git pull".
1126 die(_("Can merge only exactly one commit into "
1129 die(_("Squash commit into empty head not supported yet"));
1130 if (!allow_fast_forward
)
1131 die(_("Non-fast-forward commit does not make sense into "
1133 remote_head
= peel_to_type(argv
[0], 0, NULL
, OBJ_COMMIT
);
1135 die(_("%s - not something we can merge"), argv
[0]);
1136 read_empty(remote_head
->sha1
, 0);
1137 update_ref("initial pull", "HEAD", remote_head
->sha1
, NULL
, 0,
1141 struct strbuf merge_names
= STRBUF_INIT
;
1143 /* We are invoked directly as the first-class UI. */
1147 * All the rest are the commits being merged;
1148 * prepare the standard merge summary message to
1149 * be appended to the given message. If remote
1150 * is invalid we will die later in the common
1151 * codepath so we discard the error in this
1154 for (i
= 0; i
< argc
; i
++)
1155 merge_name(argv
[i
], &merge_names
);
1157 if (!have_message
|| shortlog_len
) {
1158 fmt_merge_msg(&merge_names
, &merge_msg
, !have_message
,
1161 strbuf_setlen(&merge_msg
, merge_msg
.len
- 1);
1165 if (head_invalid
|| !argc
)
1166 usage_with_options(builtin_merge_usage
,
1167 builtin_merge_options
);
1169 strbuf_addstr(&buf
, "merge");
1170 for (i
= 0; i
< argc
; i
++)
1171 strbuf_addf(&buf
, " %s", argv
[i
]);
1172 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
1175 for (i
= 0; i
< argc
; i
++) {
1177 struct commit
*commit
;
1179 o
= peel_to_type(argv
[i
], 0, NULL
, OBJ_COMMIT
);
1181 die(_("%s - not something we can merge"), argv
[i
]);
1182 commit
= lookup_commit(o
->sha1
);
1183 commit
->util
= (void *)argv
[i
];
1184 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1186 strbuf_addf(&buf
, "GITHEAD_%s", sha1_to_hex(o
->sha1
));
1187 setenv(buf
.buf
, argv
[i
], 1);
1191 if (!use_strategies
) {
1192 if (!remoteheads
->next
)
1193 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
1195 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
1198 for (i
= 0; i
< use_strategies_nr
; i
++) {
1199 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
1200 allow_fast_forward
= 0;
1201 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
1205 if (!remoteheads
->next
)
1206 common
= get_merge_bases(lookup_commit(head
),
1207 remoteheads
->item
, 1);
1209 struct commit_list
*list
= remoteheads
;
1210 commit_list_insert(lookup_commit(head
), &list
);
1211 common
= get_octopus_merge_bases(list
);
1215 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head
, NULL
, 0,
1219 ; /* No common ancestors found. We need a real merge. */
1220 else if (!remoteheads
->next
&& !common
->next
&&
1221 common
->item
== remoteheads
->item
) {
1223 * If head can reach all the merge then we are up to date.
1224 * but first the most common case of merging one remote.
1226 finish_up_to_date("Already up-to-date.");
1228 } else if (allow_fast_forward
&& !remoteheads
->next
&&
1230 !hashcmp(common
->item
->object
.sha1
, head
)) {
1231 /* Again the most common case of merging one remote. */
1232 struct strbuf msg
= STRBUF_INIT
;
1236 strcpy(hex
, find_unique_abbrev(head
, DEFAULT_ABBREV
));
1239 printf(_("Updating %s..%s\n"),
1241 find_unique_abbrev(remoteheads
->item
->object
.sha1
,
1243 strbuf_addstr(&msg
, "Fast-forward");
1246 " (no commit created; -m option ignored)");
1247 o
= peel_to_type(sha1_to_hex(remoteheads
->item
->object
.sha1
),
1248 0, NULL
, OBJ_COMMIT
);
1252 if (checkout_fast_forward(head
, remoteheads
->item
->object
.sha1
))
1255 finish(o
->sha1
, msg
.buf
);
1258 } else if (!remoteheads
->next
&& common
->next
)
1261 * We are not doing octopus and not fast-forward. Need
1264 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1266 * We are not doing octopus, not fast-forward, and have
1269 refresh_cache(REFRESH_QUIET
);
1270 if (allow_trivial
&& !fast_forward_only
) {
1271 /* See if it is really trivial. */
1272 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1273 printf(_("Trying really trivial in-index merge...\n"));
1274 if (!read_tree_trivial(common
->item
->object
.sha1
,
1275 head
, remoteheads
->item
->object
.sha1
))
1276 return merge_trivial();
1277 printf(_("Nope.\n"));
1281 * An octopus. If we can reach all the remote we are up
1285 struct commit_list
*j
;
1287 for (j
= remoteheads
; j
; j
= j
->next
) {
1288 struct commit_list
*common_one
;
1291 * Here we *have* to calculate the individual
1292 * merge_bases again, otherwise "git merge HEAD^
1293 * HEAD^^" would be missed.
1295 common_one
= get_merge_bases(lookup_commit(head
),
1297 if (hashcmp(common_one
->item
->object
.sha1
,
1298 j
->item
->object
.sha1
)) {
1304 finish_up_to_date("Already up-to-date. Yeeah!");
1309 if (fast_forward_only
)
1310 die(_("Not possible to fast-forward, aborting."));
1312 /* We are going to make a new commit. */
1313 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1316 * At this point, we need a real merge. No matter what strategy
1317 * we use, it would operate on the index, possibly affecting the
1318 * working tree, and when resolved cleanly, have the desired
1319 * tree in the index -- this means that the index must be in
1320 * sync with the head commit. The strategies are responsible
1323 if (use_strategies_nr
!= 1) {
1325 * Stash away the local changes so that we can try more
1330 memcpy(stash
, null_sha1
, 20);
1333 for (i
= 0; i
< use_strategies_nr
; i
++) {
1336 printf(_("Rewinding the tree to pristine...\n"));
1339 if (use_strategies_nr
!= 1)
1340 printf(_("Trying merge strategy %s...\n"),
1341 use_strategies
[i
]->name
);
1343 * Remember which strategy left the state in the working
1346 wt_strategy
= use_strategies
[i
]->name
;
1348 ret
= try_merge_strategy(use_strategies
[i
]->name
,
1350 if (!option_commit
&& !ret
) {
1353 * This is necessary here just to avoid writing
1354 * the tree, but later we will *not* exit with
1355 * status code 1 because merge_was_ok is set.
1362 * The backend exits with 1 when conflicts are
1363 * left to be resolved, with 2 when it does not
1364 * handle the given merge at all.
1367 int cnt
= evaluate_result();
1369 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1370 best_strategy
= use_strategies
[i
]->name
;
1380 /* Automerge succeeded. */
1381 write_tree_trivial(result_tree
);
1382 automerge_was_ok
= 1;
1387 * If we have a resulting tree, that means the strategy module
1388 * auto resolved the merge cleanly.
1390 if (automerge_was_ok
)
1391 return finish_automerge(common
, result_tree
, wt_strategy
);
1394 * Pick the result from the best strategy and have the user fix
1397 if (!best_strategy
) {
1399 if (use_strategies_nr
> 1)
1401 _("No merge strategy handled the merge.\n"));
1403 fprintf(stderr
, _("Merge with strategy %s failed.\n"),
1404 use_strategies
[0]->name
);
1406 } else if (best_strategy
== wt_strategy
)
1407 ; /* We already have its result in the working tree. */
1409 printf(_("Rewinding the tree to pristine...\n"));
1411 printf(_("Using the %s to prepare resolving by hand.\n"),
1413 try_merge_strategy(best_strategy
, common
, head_arg
);
1420 struct commit_list
*j
;
1422 for (j
= remoteheads
; j
; j
= j
->next
)
1423 strbuf_addf(&buf
, "%s\n",
1424 sha1_to_hex(j
->item
->object
.sha1
));
1425 fd
= open(git_path("MERGE_HEAD"), O_WRONLY
| O_CREAT
, 0666);
1427 die_errno(_("Could not open '%s' for writing"),
1428 git_path("MERGE_HEAD"));
1429 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1430 die_errno(_("Could not write to '%s'"), git_path("MERGE_HEAD"));
1432 strbuf_addch(&merge_msg
, '\n');
1434 fd
= open(git_path("MERGE_MODE"), O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
1436 die_errno(_("Could not open '%s' for writing"),
1437 git_path("MERGE_MODE"));
1439 if (!allow_fast_forward
)
1440 strbuf_addf(&buf
, "no-ff");
1441 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1442 die_errno(_("Could not write to '%s'"), git_path("MERGE_MODE"));
1447 fprintf(stderr
, _("Automatic merge went well; "
1448 "stopped before committing as requested\n"));
1451 return suggest_conflicts(option_renormalize
);