4 * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
6 * Based on git-merge.sh by Junio C Hamano.
10 #include "parse-options.h"
12 #include "run-command.h"
18 #include "unpack-trees.h"
19 #include "cache-tree.h"
26 #include "merge-recursive.h"
27 #include "resolve-undo.h"
30 #define DEFAULT_TWOHEAD (1<<0)
31 #define DEFAULT_OCTOPUS (1<<1)
32 #define NO_FAST_FORWARD (1<<2)
33 #define NO_TRIVIAL (1<<3)
40 static const char * const builtin_merge_usage
[] = {
41 "git merge [options] [<commit>...]",
42 "git merge [options] <msg> HEAD <commit>",
47 static int show_diffstat
= 1, shortlog_len
, squash
;
48 static int option_commit
= 1, allow_fast_forward
= 1;
49 static int fast_forward_only
, option_edit
= -1;
50 static int allow_trivial
= 1, have_message
;
51 static struct strbuf merge_msg
;
52 static struct commit_list
*remoteheads
;
53 static struct strategy
**use_strategies
;
54 static size_t use_strategies_nr
, use_strategies_alloc
;
55 static const char **xopts
;
56 static size_t xopts_nr
, xopts_alloc
;
57 static const char *branch
;
58 static char *branch_mergeoptions
;
59 static int option_renormalize
;
61 static int allow_rerere_auto
;
62 static int abort_current_merge
;
63 static int show_progress
= -1;
64 static int default_to_upstream
;
66 static struct strategy all_strategy
[] = {
67 { "recursive", DEFAULT_TWOHEAD
| NO_TRIVIAL
},
68 { "octopus", DEFAULT_OCTOPUS
},
70 { "ours", NO_FAST_FORWARD
| NO_TRIVIAL
},
71 { "subtree", NO_FAST_FORWARD
| NO_TRIVIAL
},
74 static const char *pull_twohead
, *pull_octopus
;
76 static int option_parse_message(const struct option
*opt
,
77 const char *arg
, int unset
)
79 struct strbuf
*buf
= opt
->value
;
82 strbuf_setlen(buf
, 0);
84 strbuf_addf(buf
, "%s%s", buf
->len
? "\n\n" : "", arg
);
87 return error(_("switch `m' requires a value"));
91 static struct strategy
*get_strategy(const char *name
)
95 static struct cmdnames main_cmds
, other_cmds
;
101 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
102 if (!strcmp(name
, all_strategy
[i
].name
))
103 return &all_strategy
[i
];
106 struct cmdnames not_strategies
;
109 memset(¬_strategies
, 0, sizeof(struct cmdnames
));
110 load_command_list("git-merge-", &main_cmds
, &other_cmds
);
111 for (i
= 0; i
< main_cmds
.cnt
; i
++) {
113 struct cmdname
*ent
= main_cmds
.names
[i
];
114 for (j
= 0; j
< ARRAY_SIZE(all_strategy
); j
++)
115 if (!strncmp(ent
->name
, all_strategy
[j
].name
, ent
->len
)
116 && !all_strategy
[j
].name
[ent
->len
])
119 add_cmdname(¬_strategies
, ent
->name
, ent
->len
);
121 exclude_cmds(&main_cmds
, ¬_strategies
);
123 if (!is_in_cmdlist(&main_cmds
, name
) && !is_in_cmdlist(&other_cmds
, name
)) {
124 fprintf(stderr
, _("Could not find merge strategy '%s'.\n"), name
);
125 fprintf(stderr
, _("Available strategies are:"));
126 for (i
= 0; i
< main_cmds
.cnt
; i
++)
127 fprintf(stderr
, " %s", main_cmds
.names
[i
]->name
);
128 fprintf(stderr
, ".\n");
129 if (other_cmds
.cnt
) {
130 fprintf(stderr
, _("Available custom strategies are:"));
131 for (i
= 0; i
< other_cmds
.cnt
; i
++)
132 fprintf(stderr
, " %s", other_cmds
.names
[i
]->name
);
133 fprintf(stderr
, ".\n");
138 ret
= xcalloc(1, sizeof(struct strategy
));
139 ret
->name
= xstrdup(name
);
140 ret
->attr
= NO_TRIVIAL
;
144 static void append_strategy(struct strategy
*s
)
146 ALLOC_GROW(use_strategies
, use_strategies_nr
+ 1, use_strategies_alloc
);
147 use_strategies
[use_strategies_nr
++] = s
;
150 static int option_parse_strategy(const struct option
*opt
,
151 const char *name
, int unset
)
156 append_strategy(get_strategy(name
));
160 static int option_parse_x(const struct option
*opt
,
161 const char *arg
, int unset
)
166 ALLOC_GROW(xopts
, xopts_nr
+ 1, xopts_alloc
);
167 xopts
[xopts_nr
++] = xstrdup(arg
);
171 static int option_parse_n(const struct option
*opt
,
172 const char *arg
, int unset
)
174 show_diffstat
= unset
;
178 static struct option builtin_merge_options
[] = {
179 { OPTION_CALLBACK
, 'n', NULL
, NULL
, NULL
,
180 "do not show a diffstat at the end of the merge",
181 PARSE_OPT_NOARG
, option_parse_n
},
182 OPT_BOOLEAN(0, "stat", &show_diffstat
,
183 "show a diffstat at the end of the merge"),
184 OPT_BOOLEAN(0, "summary", &show_diffstat
, "(synonym to --stat)"),
185 { OPTION_INTEGER
, 0, "log", &shortlog_len
, "n",
186 "add (at most <n>) entries from shortlog to merge commit message",
187 PARSE_OPT_OPTARG
, NULL
, DEFAULT_MERGE_LOG_LEN
},
188 OPT_BOOLEAN(0, "squash", &squash
,
189 "create a single commit instead of doing a merge"),
190 OPT_BOOLEAN(0, "commit", &option_commit
,
191 "perform a commit if the merge succeeds (default)"),
192 OPT_BOOL('e', "edit", &option_edit
,
193 "edit message before committing"),
194 OPT_BOOLEAN(0, "ff", &allow_fast_forward
,
195 "allow fast-forward (default)"),
196 OPT_BOOLEAN(0, "ff-only", &fast_forward_only
,
197 "abort if fast-forward is not possible"),
198 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto
),
199 OPT_CALLBACK('s', "strategy", &use_strategies
, "strategy",
200 "merge strategy to use", option_parse_strategy
),
201 OPT_CALLBACK('X', "strategy-option", &xopts
, "option=value",
202 "option for selected merge strategy", option_parse_x
),
203 OPT_CALLBACK('m', "message", &merge_msg
, "message",
204 "merge commit message (for a non-fast-forward merge)",
205 option_parse_message
),
206 OPT__VERBOSITY(&verbosity
),
207 OPT_BOOLEAN(0, "abort", &abort_current_merge
,
208 "abort the current in-progress merge"),
209 OPT_SET_INT(0, "progress", &show_progress
, "force progress reporting", 1),
213 /* Cleans up metadata that is uninteresting after a succeeded merge. */
214 static void drop_save(void)
216 unlink(git_path("MERGE_HEAD"));
217 unlink(git_path("MERGE_MSG"));
218 unlink(git_path("MERGE_MODE"));
221 static int save_state(unsigned char *stash
)
224 struct child_process cp
;
225 struct strbuf buffer
= STRBUF_INIT
;
226 const char *argv
[] = {"stash", "create", NULL
};
228 memset(&cp
, 0, sizeof(cp
));
233 if (start_command(&cp
))
234 die(_("could not run stash."));
235 len
= strbuf_read(&buffer
, cp
.out
, 1024);
238 if (finish_command(&cp
) || len
< 0)
239 die(_("stash failed"));
240 else if (!len
) /* no changes */
242 strbuf_setlen(&buffer
, buffer
.len
-1);
243 if (get_sha1(buffer
.buf
, stash
))
244 die(_("not a valid object: %s"), buffer
.buf
);
248 static void read_empty(unsigned const char *sha1
, int verbose
)
253 args
[i
++] = "read-tree";
258 args
[i
++] = EMPTY_TREE_SHA1_HEX
;
259 args
[i
++] = sha1_to_hex(sha1
);
262 if (run_command_v_opt(args
, RUN_GIT_CMD
))
263 die(_("read-tree failed"));
266 static void reset_hard(unsigned const char *sha1
, int verbose
)
271 args
[i
++] = "read-tree";
274 args
[i
++] = "--reset";
276 args
[i
++] = sha1_to_hex(sha1
);
279 if (run_command_v_opt(args
, RUN_GIT_CMD
))
280 die(_("read-tree failed"));
283 static void restore_state(const unsigned char *head
,
284 const unsigned char *stash
)
286 struct strbuf sb
= STRBUF_INIT
;
287 const char *args
[] = { "stash", "apply", NULL
, NULL
};
289 if (is_null_sha1(stash
))
294 args
[2] = sha1_to_hex(stash
);
297 * It is OK to ignore error here, for example when there was
298 * nothing to restore.
300 run_command_v_opt(args
, RUN_GIT_CMD
);
303 refresh_cache(REFRESH_QUIET
);
306 /* This is called when no merge was necessary. */
307 static void finish_up_to_date(const char *msg
)
310 printf("%s%s\n", squash
? _(" (nothing to squash)") : "", msg
);
314 static void squash_message(struct commit
*commit
)
317 struct strbuf out
= STRBUF_INIT
;
318 struct commit_list
*j
;
320 struct pretty_print_context ctx
= {0};
322 printf(_("Squash commit -- not updating HEAD\n"));
323 fd
= open(git_path("SQUASH_MSG"), O_WRONLY
| O_CREAT
, 0666);
325 die_errno(_("Could not write to '%s'"), git_path("SQUASH_MSG"));
327 init_revisions(&rev
, NULL
);
328 rev
.ignore_merges
= 1;
329 rev
.commit_format
= CMIT_FMT_MEDIUM
;
331 commit
->object
.flags
|= UNINTERESTING
;
332 add_pending_object(&rev
, &commit
->object
, NULL
);
334 for (j
= remoteheads
; j
; j
= j
->next
)
335 add_pending_object(&rev
, &j
->item
->object
, NULL
);
337 setup_revisions(0, NULL
, &rev
, NULL
);
338 if (prepare_revision_walk(&rev
))
339 die(_("revision walk setup failed"));
341 ctx
.abbrev
= rev
.abbrev
;
342 ctx
.date_mode
= rev
.date_mode
;
343 ctx
.fmt
= rev
.commit_format
;
345 strbuf_addstr(&out
, "Squashed commit of the following:\n");
346 while ((commit
= get_revision(&rev
)) != NULL
) {
347 strbuf_addch(&out
, '\n');
348 strbuf_addf(&out
, "commit %s\n",
349 sha1_to_hex(commit
->object
.sha1
));
350 pretty_print_commit(&ctx
, commit
, &out
);
352 if (write(fd
, out
.buf
, out
.len
) < 0)
353 die_errno(_("Writing SQUASH_MSG"));
355 die_errno(_("Finishing SQUASH_MSG"));
356 strbuf_release(&out
);
359 static void finish(struct commit
*head_commit
,
360 const unsigned char *new_head
, const char *msg
)
362 struct strbuf reflog_message
= STRBUF_INIT
;
363 const unsigned char *head
= head_commit
->object
.sha1
;
366 strbuf_addstr(&reflog_message
, getenv("GIT_REFLOG_ACTION"));
370 strbuf_addf(&reflog_message
, "%s: %s",
371 getenv("GIT_REFLOG_ACTION"), msg
);
374 squash_message(head_commit
);
376 if (verbosity
>= 0 && !merge_msg
.len
)
377 printf(_("No merge message -- not updating HEAD\n"));
379 const char *argv_gc_auto
[] = { "gc", "--auto", NULL
};
380 update_ref(reflog_message
.buf
, "HEAD",
384 * We ignore errors in 'gc --auto', since the
385 * user should see them.
387 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
390 if (new_head
&& show_diffstat
) {
391 struct diff_options opts
;
393 opts
.output_format
|=
394 DIFF_FORMAT_SUMMARY
| DIFF_FORMAT_DIFFSTAT
;
395 opts
.detect_rename
= DIFF_DETECT_RENAME
;
396 if (diff_setup_done(&opts
) < 0)
397 die(_("diff_setup_done failed"));
398 diff_tree_sha1(head
, new_head
, "", &opts
);
403 /* Run a post-merge hook */
404 run_hook(NULL
, "post-merge", squash
? "1" : "0", NULL
);
406 strbuf_release(&reflog_message
);
409 /* Get the name for the merge commit's message. */
410 static void merge_name(const char *remote
, struct strbuf
*msg
)
412 struct commit
*remote_head
;
413 unsigned char branch_head
[20], buf_sha
[20];
414 struct strbuf buf
= STRBUF_INIT
;
415 struct strbuf bname
= STRBUF_INIT
;
420 strbuf_branchname(&bname
, remote
);
423 memset(branch_head
, 0, sizeof(branch_head
));
424 remote_head
= get_merge_parent(remote
);
426 die(_("'%s' does not point to a commit"), remote
);
428 if (dwim_ref(remote
, strlen(remote
), branch_head
, &found_ref
) > 0) {
429 if (!prefixcmp(found_ref
, "refs/heads/")) {
430 strbuf_addf(msg
, "%s\t\tbranch '%s' of .\n",
431 sha1_to_hex(branch_head
), remote
);
434 if (!prefixcmp(found_ref
, "refs/tags/")) {
435 strbuf_addf(msg
, "%s\t\ttag '%s' of .\n",
436 sha1_to_hex(branch_head
), remote
);
439 if (!prefixcmp(found_ref
, "refs/remotes/")) {
440 strbuf_addf(msg
, "%s\t\tremote-tracking branch '%s' of .\n",
441 sha1_to_hex(branch_head
), remote
);
446 /* See if remote matches <name>^^^.. or <name>~<number> */
447 for (len
= 0, ptr
= remote
+ strlen(remote
);
448 remote
< ptr
&& ptr
[-1] == '^';
455 ptr
= strrchr(remote
, '~');
457 int seen_nonzero
= 0;
460 while (*++ptr
&& isdigit(*ptr
)) {
461 seen_nonzero
|= (*ptr
!= '0');
465 len
= 0; /* not ...~<number> */
466 else if (seen_nonzero
)
469 early
= 1; /* "name~" is "name~1"! */
473 struct strbuf truname
= STRBUF_INIT
;
474 strbuf_addstr(&truname
, "refs/heads/");
475 strbuf_addstr(&truname
, remote
);
476 strbuf_setlen(&truname
, truname
.len
- len
);
477 if (resolve_ref(truname
.buf
, buf_sha
, 1, NULL
)) {
479 "%s\t\tbranch '%s'%s of .\n",
480 sha1_to_hex(remote_head
->object
.sha1
),
482 (early
? " (early part)" : ""));
483 strbuf_release(&truname
);
488 if (!strcmp(remote
, "FETCH_HEAD") &&
489 !access(git_path("FETCH_HEAD"), R_OK
)) {
491 struct strbuf line
= STRBUF_INIT
;
494 fp
= fopen(git_path("FETCH_HEAD"), "r");
496 die_errno(_("could not open '%s' for reading"),
497 git_path("FETCH_HEAD"));
498 strbuf_getline(&line
, fp
, '\n');
500 ptr
= strstr(line
.buf
, "\tnot-for-merge\t");
502 strbuf_remove(&line
, ptr
-line
.buf
+1, 13);
503 strbuf_addbuf(msg
, &line
);
504 strbuf_release(&line
);
507 strbuf_addf(msg
, "%s\t\tcommit '%s'\n",
508 sha1_to_hex(remote_head
->object
.sha1
), remote
);
510 strbuf_release(&buf
);
511 strbuf_release(&bname
);
514 static void parse_branch_merge_options(char *bmo
)
521 argc
= split_cmdline(bmo
, &argv
);
523 die(_("Bad branch.%s.mergeoptions string: %s"), branch
,
524 split_cmdline_strerror(argc
));
525 argv
= xrealloc(argv
, sizeof(*argv
) * (argc
+ 2));
526 memmove(argv
+ 1, argv
, sizeof(*argv
) * (argc
+ 1));
528 argv
[0] = "branch.*.mergeoptions";
529 parse_options(argc
, argv
, NULL
, builtin_merge_options
,
530 builtin_merge_usage
, 0);
534 static int git_merge_config(const char *k
, const char *v
, void *cb
)
536 if (branch
&& !prefixcmp(k
, "branch.") &&
537 !prefixcmp(k
+ 7, branch
) &&
538 !strcmp(k
+ 7 + strlen(branch
), ".mergeoptions")) {
539 free(branch_mergeoptions
);
540 branch_mergeoptions
= xstrdup(v
);
544 if (!strcmp(k
, "merge.diffstat") || !strcmp(k
, "merge.stat"))
545 show_diffstat
= git_config_bool(k
, v
);
546 else if (!strcmp(k
, "pull.twohead"))
547 return git_config_string(&pull_twohead
, k
, v
);
548 else if (!strcmp(k
, "pull.octopus"))
549 return git_config_string(&pull_octopus
, k
, v
);
550 else if (!strcmp(k
, "merge.renormalize"))
551 option_renormalize
= git_config_bool(k
, v
);
552 else if (!strcmp(k
, "merge.log") || !strcmp(k
, "merge.summary")) {
554 shortlog_len
= git_config_bool_or_int(k
, v
, &is_bool
);
555 if (!is_bool
&& shortlog_len
< 0)
556 return error(_("%s: negative length %s"), k
, v
);
557 if (is_bool
&& shortlog_len
)
558 shortlog_len
= DEFAULT_MERGE_LOG_LEN
;
560 } else if (!strcmp(k
, "merge.ff")) {
561 int boolval
= git_config_maybe_bool(k
, v
);
563 allow_fast_forward
= boolval
;
564 } else if (v
&& !strcmp(v
, "only")) {
565 allow_fast_forward
= 1;
566 fast_forward_only
= 1;
567 } /* do not barf on values from future versions of git */
569 } else if (!strcmp(k
, "merge.defaulttoupstream")) {
570 default_to_upstream
= git_config_bool(k
, v
);
573 return git_diff_ui_config(k
, v
, cb
);
576 static int read_tree_trivial(unsigned char *common
, unsigned char *head
,
580 struct tree
*trees
[MAX_UNPACK_TREES
];
581 struct tree_desc t
[MAX_UNPACK_TREES
];
582 struct unpack_trees_options opts
;
584 memset(&opts
, 0, sizeof(opts
));
586 opts
.src_index
= &the_index
;
587 opts
.dst_index
= &the_index
;
589 opts
.verbose_update
= 1;
590 opts
.trivial_merges_only
= 1;
592 trees
[nr_trees
] = parse_tree_indirect(common
);
593 if (!trees
[nr_trees
++])
595 trees
[nr_trees
] = parse_tree_indirect(head
);
596 if (!trees
[nr_trees
++])
598 trees
[nr_trees
] = parse_tree_indirect(one
);
599 if (!trees
[nr_trees
++])
601 opts
.fn
= threeway_merge
;
602 cache_tree_free(&active_cache_tree
);
603 for (i
= 0; i
< nr_trees
; i
++) {
604 parse_tree(trees
[i
]);
605 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
607 if (unpack_trees(nr_trees
, t
, &opts
))
612 static void write_tree_trivial(unsigned char *sha1
)
614 if (write_cache_as_tree(sha1
, 0, NULL
))
615 die(_("git write-tree failed to write a tree"));
618 static const char *merge_argument(struct commit
*commit
)
621 return sha1_to_hex(commit
->object
.sha1
);
623 return EMPTY_TREE_SHA1_HEX
;
626 int try_merge_command(const char *strategy
, size_t xopts_nr
,
627 const char **xopts
, struct commit_list
*common
,
628 const char *head_arg
, struct commit_list
*remotes
)
631 int i
= 0, x
= 0, ret
;
632 struct commit_list
*j
;
633 struct strbuf buf
= STRBUF_INIT
;
635 args
= xmalloc((4 + xopts_nr
+ commit_list_count(common
) +
636 commit_list_count(remotes
)) * sizeof(char *));
637 strbuf_addf(&buf
, "merge-%s", strategy
);
639 for (x
= 0; x
< xopts_nr
; x
++) {
640 char *s
= xmalloc(strlen(xopts
[x
])+2+1);
642 strcpy(s
+2, xopts
[x
]);
645 for (j
= common
; j
; j
= j
->next
)
646 args
[i
++] = xstrdup(merge_argument(j
->item
));
648 args
[i
++] = head_arg
;
649 for (j
= remotes
; j
; j
= j
->next
)
650 args
[i
++] = xstrdup(merge_argument(j
->item
));
652 ret
= run_command_v_opt(args
, RUN_GIT_CMD
);
653 strbuf_release(&buf
);
655 for (x
= 0; x
< xopts_nr
; x
++)
656 free((void *)args
[i
++]);
657 for (j
= common
; j
; j
= j
->next
)
658 free((void *)args
[i
++]);
660 for (j
= remotes
; j
; j
= j
->next
)
661 free((void *)args
[i
++]);
664 if (read_cache() < 0)
665 die(_("failed to read the cache"));
666 resolve_undo_clear();
671 static int try_merge_strategy(const char *strategy
, struct commit_list
*common
,
672 struct commit
*head
, const char *head_arg
)
675 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
677 index_fd
= hold_locked_index(lock
, 1);
678 refresh_cache(REFRESH_QUIET
);
679 if (active_cache_changed
&&
680 (write_cache(index_fd
, active_cache
, active_nr
) ||
681 commit_locked_index(lock
)))
682 return error(_("Unable to write index."));
683 rollback_lock_file(lock
);
685 if (!strcmp(strategy
, "recursive") || !strcmp(strategy
, "subtree")) {
687 struct commit
*result
;
688 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
690 struct commit_list
*reversed
= NULL
;
691 struct merge_options o
;
692 struct commit_list
*j
;
694 if (remoteheads
->next
) {
695 error(_("Not handling anything other than two heads merge."));
699 init_merge_options(&o
);
700 if (!strcmp(strategy
, "subtree"))
701 o
.subtree_shift
= "";
703 o
.renormalize
= option_renormalize
;
704 o
.show_rename_progress
=
705 show_progress
== -1 ? isatty(2) : show_progress
;
707 for (x
= 0; x
< xopts_nr
; x
++)
708 if (parse_merge_opt(&o
, xopts
[x
]))
709 die(_("Unknown option for merge-recursive: -X%s"), xopts
[x
]);
711 o
.branch1
= head_arg
;
712 o
.branch2
= merge_remote_util(remoteheads
->item
)->name
;
714 for (j
= common
; j
; j
= j
->next
)
715 commit_list_insert(j
->item
, &reversed
);
717 index_fd
= hold_locked_index(lock
, 1);
718 clean
= merge_recursive(&o
, head
,
719 remoteheads
->item
, reversed
, &result
);
720 if (active_cache_changed
&&
721 (write_cache(index_fd
, active_cache
, active_nr
) ||
722 commit_locked_index(lock
)))
723 die (_("unable to write %s"), get_index_file());
724 rollback_lock_file(lock
);
725 return clean
? 0 : 1;
727 return try_merge_command(strategy
, xopts_nr
, xopts
,
728 common
, head_arg
, remoteheads
);
732 static void count_diff_files(struct diff_queue_struct
*q
,
733 struct diff_options
*opt
, void *data
)
740 static int count_unmerged_entries(void)
744 for (i
= 0; i
< active_nr
; i
++)
745 if (ce_stage(active_cache
[i
]))
751 int checkout_fast_forward(const unsigned char *head
, const unsigned char *remote
)
753 struct tree
*trees
[MAX_UNPACK_TREES
];
754 struct unpack_trees_options opts
;
755 struct tree_desc t
[MAX_UNPACK_TREES
];
756 int i
, fd
, nr_trees
= 0;
757 struct dir_struct dir
;
758 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
760 refresh_cache(REFRESH_QUIET
);
762 fd
= hold_locked_index(lock_file
, 1);
764 memset(&trees
, 0, sizeof(trees
));
765 memset(&opts
, 0, sizeof(opts
));
766 memset(&t
, 0, sizeof(t
));
767 memset(&dir
, 0, sizeof(dir
));
768 dir
.flags
|= DIR_SHOW_IGNORED
;
769 dir
.exclude_per_dir
= ".gitignore";
773 opts
.src_index
= &the_index
;
774 opts
.dst_index
= &the_index
;
776 opts
.verbose_update
= 1;
778 opts
.fn
= twoway_merge
;
779 setup_unpack_trees_porcelain(&opts
, "merge");
781 trees
[nr_trees
] = parse_tree_indirect(head
);
782 if (!trees
[nr_trees
++])
784 trees
[nr_trees
] = parse_tree_indirect(remote
);
785 if (!trees
[nr_trees
++])
787 for (i
= 0; i
< nr_trees
; i
++) {
788 parse_tree(trees
[i
]);
789 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
791 if (unpack_trees(nr_trees
, t
, &opts
))
793 if (write_cache(fd
, active_cache
, active_nr
) ||
794 commit_locked_index(lock_file
))
795 die(_("unable to write new index file"));
799 static void split_merge_strategies(const char *string
, struct strategy
**list
,
807 buf
= xstrdup(string
);
812 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
813 (*list
)[(*nr
)++].name
= xstrdup(q
);
818 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
819 (*list
)[(*nr
)++].name
= xstrdup(q
);
825 static void add_strategies(const char *string
, unsigned attr
)
827 struct strategy
*list
= NULL
;
828 int list_alloc
= 0, list_nr
= 0, i
;
830 memset(&list
, 0, sizeof(list
));
831 split_merge_strategies(string
, &list
, &list_nr
, &list_alloc
);
833 for (i
= 0; i
< list_nr
; i
++)
834 append_strategy(get_strategy(list
[i
].name
));
837 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
838 if (all_strategy
[i
].attr
& attr
)
839 append_strategy(&all_strategy
[i
]);
843 static void write_merge_msg(struct strbuf
*msg
)
845 int fd
= open(git_path("MERGE_MSG"), O_WRONLY
| O_CREAT
, 0666);
847 die_errno(_("Could not open '%s' for writing"),
848 git_path("MERGE_MSG"));
849 if (write_in_full(fd
, msg
->buf
, msg
->len
) != msg
->len
)
850 die_errno(_("Could not write to '%s'"), git_path("MERGE_MSG"));
854 static void read_merge_msg(struct strbuf
*msg
)
857 if (strbuf_read_file(msg
, git_path("MERGE_MSG"), 0) < 0)
858 die_errno(_("Could not read from '%s'"), git_path("MERGE_MSG"));
861 static void write_merge_state(void);
862 static void abort_commit(const char *err_msg
)
865 error("%s", err_msg
);
867 _("Not committing merge; use 'git commit' to complete the merge.\n"));
872 static void prepare_to_commit(void)
874 struct strbuf msg
= STRBUF_INIT
;
875 strbuf_addbuf(&msg
, &merge_msg
);
876 strbuf_addch(&msg
, '\n');
877 write_merge_msg(&msg
);
878 run_hook(get_index_file(), "prepare-commit-msg",
879 git_path("MERGE_MSG"), "merge", NULL
, NULL
);
880 if (0 < option_edit
) {
881 if (launch_editor(git_path("MERGE_MSG"), NULL
, NULL
))
884 read_merge_msg(&msg
);
885 stripspace(&msg
, 0 < option_edit
);
887 abort_commit(_("Empty commit message."));
888 strbuf_release(&merge_msg
);
889 strbuf_addbuf(&merge_msg
, &msg
);
890 strbuf_release(&msg
);
893 static int merge_trivial(struct commit
*head
)
895 unsigned char result_tree
[20], result_commit
[20];
896 struct commit_list
*parent
= xmalloc(sizeof(*parent
));
898 write_tree_trivial(result_tree
);
899 printf(_("Wonderful.\n"));
901 parent
->next
= xmalloc(sizeof(*parent
->next
));
902 parent
->next
->item
= remoteheads
->item
;
903 parent
->next
->next
= NULL
;
905 commit_tree(merge_msg
.buf
, result_tree
, parent
, result_commit
, NULL
);
906 finish(head
, result_commit
, "In-index merge");
911 static int finish_automerge(struct commit
*head
,
912 struct commit_list
*common
,
913 unsigned char *result_tree
,
914 const char *wt_strategy
)
916 struct commit_list
*parents
= NULL
, *j
;
917 struct strbuf buf
= STRBUF_INIT
;
918 unsigned char result_commit
[20];
920 free_commit_list(common
);
921 if (allow_fast_forward
) {
922 parents
= remoteheads
;
923 commit_list_insert(head
, &parents
);
924 parents
= reduce_heads(parents
);
926 struct commit_list
**pptr
= &parents
;
928 pptr
= &commit_list_insert(head
,
930 for (j
= remoteheads
; j
; j
= j
->next
)
931 pptr
= &commit_list_insert(j
->item
, pptr
)->next
;
933 strbuf_addch(&merge_msg
, '\n');
935 free_commit_list(remoteheads
);
936 commit_tree(merge_msg
.buf
, result_tree
, parents
, result_commit
, NULL
);
937 strbuf_addf(&buf
, "Merge made by the '%s' strategy.", wt_strategy
);
938 finish(head
, result_commit
, buf
.buf
);
939 strbuf_release(&buf
);
944 static int suggest_conflicts(int renormalizing
)
949 fp
= fopen(git_path("MERGE_MSG"), "a");
951 die_errno(_("Could not open '%s' for writing"),
952 git_path("MERGE_MSG"));
953 fprintf(fp
, "\nConflicts:\n");
954 for (pos
= 0; pos
< active_nr
; pos
++) {
955 struct cache_entry
*ce
= active_cache
[pos
];
958 fprintf(fp
, "\t%s\n", ce
->name
);
959 while (pos
+ 1 < active_nr
&&
961 active_cache
[pos
+ 1]->name
))
966 rerere(allow_rerere_auto
);
967 printf(_("Automatic merge failed; "
968 "fix conflicts and then commit the result.\n"));
972 static struct commit
*is_old_style_invocation(int argc
, const char **argv
,
973 const unsigned char *head
)
975 struct commit
*second_token
= NULL
;
977 unsigned char second_sha1
[20];
979 if (get_sha1(argv
[1], second_sha1
))
981 second_token
= lookup_commit_reference_gently(second_sha1
, 0);
983 die(_("'%s' is not a commit"), argv
[1]);
984 if (hashcmp(second_token
->object
.sha1
, head
))
990 static int evaluate_result(void)
995 /* Check how many files differ. */
996 init_revisions(&rev
, "");
997 setup_revisions(0, NULL
, &rev
, NULL
);
998 rev
.diffopt
.output_format
|=
999 DIFF_FORMAT_CALLBACK
;
1000 rev
.diffopt
.format_callback
= count_diff_files
;
1001 rev
.diffopt
.format_callback_data
= &cnt
;
1002 run_diff_files(&rev
, 0);
1005 * Check how many unmerged entries are
1008 cnt
+= count_unmerged_entries();
1014 * Pretend as if the user told us to merge with the tracking
1015 * branch we have for the upstream of the current branch
1017 static int setup_with_upstream(const char ***argv
)
1019 struct branch
*branch
= branch_get(NULL
);
1024 die(_("No current branch."));
1025 if (!branch
->remote
)
1026 die(_("No remote for the current branch."));
1027 if (!branch
->merge_nr
)
1028 die(_("No default upstream defined for the current branch."));
1030 args
= xcalloc(branch
->merge_nr
+ 1, sizeof(char *));
1031 for (i
= 0; i
< branch
->merge_nr
; i
++) {
1032 if (!branch
->merge
[i
]->dst
)
1033 die(_("No remote tracking branch for %s from %s"),
1034 branch
->merge
[i
]->src
, branch
->remote_name
);
1035 args
[i
] = branch
->merge
[i
]->dst
;
1042 static void write_merge_state(void)
1045 struct commit_list
*j
;
1046 struct strbuf buf
= STRBUF_INIT
;
1048 for (j
= remoteheads
; j
; j
= j
->next
) {
1049 unsigned const char *sha1
;
1050 struct commit
*c
= j
->item
;
1051 if (c
->util
&& merge_remote_util(c
)->obj
) {
1052 sha1
= merge_remote_util(c
)->obj
->sha1
;
1054 sha1
= c
->object
.sha1
;
1056 strbuf_addf(&buf
, "%s\n", sha1_to_hex(sha1
));
1058 fd
= open(git_path("MERGE_HEAD"), O_WRONLY
| O_CREAT
, 0666);
1060 die_errno(_("Could not open '%s' for writing"),
1061 git_path("MERGE_HEAD"));
1062 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1063 die_errno(_("Could not write to '%s'"), git_path("MERGE_HEAD"));
1065 strbuf_addch(&merge_msg
, '\n');
1066 write_merge_msg(&merge_msg
);
1067 fd
= open(git_path("MERGE_MODE"), O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
1069 die_errno(_("Could not open '%s' for writing"),
1070 git_path("MERGE_MODE"));
1072 if (!allow_fast_forward
)
1073 strbuf_addf(&buf
, "no-ff");
1074 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1075 die_errno(_("Could not write to '%s'"), git_path("MERGE_MODE"));
1079 static int default_edit_option(void)
1081 static const char name
[] = "GIT_MERGE_AUTOEDIT";
1082 const char *e
= getenv(name
);
1083 struct stat st_stdin
, st_stdout
;
1086 /* an explicit -m msg without --[no-]edit */
1090 int v
= git_config_maybe_bool(name
, e
);
1092 die("Bad value '%s' in environment '%s'", e
, name
);
1096 /* Use editor if stdin and stdout are the same and is a tty */
1097 return (!fstat(0, &st_stdin
) &&
1098 !fstat(1, &st_stdout
) &&
1100 st_stdin
.st_dev
== st_stdout
.st_dev
&&
1101 st_stdin
.st_ino
== st_stdout
.st_ino
&&
1102 st_stdin
.st_mode
== st_stdout
.st_mode
);
1106 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
1108 unsigned char result_tree
[20];
1109 unsigned char stash
[20];
1110 unsigned char head_sha1
[20];
1111 struct commit
*head_commit
;
1112 struct strbuf buf
= STRBUF_INIT
;
1113 const char *head_arg
;
1115 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
1116 struct commit_list
*common
= NULL
;
1117 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
1118 struct commit_list
**remotes
= &remoteheads
;
1120 if (argc
== 2 && !strcmp(argv
[1], "-h"))
1121 usage_with_options(builtin_merge_usage
, builtin_merge_options
);
1124 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1127 branch
= resolve_ref("HEAD", head_sha1
, 0, &flag
);
1128 if (branch
&& !prefixcmp(branch
, "refs/heads/"))
1130 if (!branch
|| is_null_sha1(head_sha1
))
1133 head_commit
= lookup_commit_or_die(head_sha1
, "HEAD");
1135 git_config(git_merge_config
, NULL
);
1137 if (branch_mergeoptions
)
1138 parse_branch_merge_options(branch_mergeoptions
);
1139 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
1140 builtin_merge_usage
, 0);
1142 if (verbosity
< 0 && show_progress
== -1)
1145 if (abort_current_merge
) {
1147 const char *nargv
[] = {"reset", "--merge", NULL
};
1149 if (!file_exists(git_path("MERGE_HEAD")))
1150 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1152 /* Invoke 'git reset --merge' */
1153 return cmd_reset(nargc
, nargv
, prefix
);
1156 if (read_cache_unmerged())
1157 die_resolve_conflict("merge");
1159 if (file_exists(git_path("MERGE_HEAD"))) {
1161 * There is no unmerged entry, don't advise 'git
1162 * add/rm <file>', just 'git commit'.
1164 if (advice_resolve_conflict
)
1165 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1166 "Please, commit your changes before you can merge."));
1168 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1170 if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
1171 if (advice_resolve_conflict
)
1172 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1173 "Please, commit your changes before you can merge."));
1175 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1177 resolve_undo_clear();
1183 if (!allow_fast_forward
)
1184 die(_("You cannot combine --squash with --no-ff."));
1188 if (!allow_fast_forward
&& fast_forward_only
)
1189 die(_("You cannot combine --no-ff with --ff-only."));
1191 if (!abort_current_merge
) {
1192 if (!argc
&& default_to_upstream
)
1193 argc
= setup_with_upstream(&argv
);
1194 else if (argc
== 1 && !strcmp(argv
[0], "-"))
1198 usage_with_options(builtin_merge_usage
,
1199 builtin_merge_options
);
1202 * This could be traditional "merge <msg> HEAD <commit>..." and
1203 * the way we can tell it is to see if the second token is HEAD,
1204 * but some people might have misused the interface and used a
1205 * committish that is the same as HEAD there instead.
1206 * Traditional format never would have "-m" so it is an
1207 * additional safety measure to check for it.
1210 if (!have_message
&& head_commit
&&
1211 is_old_style_invocation(argc
, argv
, head_commit
->object
.sha1
)) {
1212 strbuf_addstr(&merge_msg
, argv
[0]);
1216 } else if (!head_commit
) {
1217 struct commit
*remote_head
;
1219 * If the merged head is a valid one there is no reason
1220 * to forbid "git merge" into a branch yet to be born.
1221 * We do the same for "git pull".
1224 die(_("Can merge only exactly one commit into "
1227 die(_("Squash commit into empty head not supported yet"));
1228 if (!allow_fast_forward
)
1229 die(_("Non-fast-forward commit does not make sense into "
1231 remote_head
= get_merge_parent(argv
[0]);
1233 die(_("%s - not something we can merge"), argv
[0]);
1234 read_empty(remote_head
->object
.sha1
, 0);
1235 update_ref("initial pull", "HEAD", remote_head
->object
.sha1
,
1236 NULL
, 0, DIE_ON_ERR
);
1239 struct strbuf merge_names
= STRBUF_INIT
;
1241 /* We are invoked directly as the first-class UI. */
1245 * All the rest are the commits being merged; prepare
1246 * the standard merge summary message to be appended
1247 * to the given message.
1249 for (i
= 0; i
< argc
; i
++)
1250 merge_name(argv
[i
], &merge_names
);
1252 if (!have_message
|| shortlog_len
) {
1253 struct fmt_merge_msg_opts opts
;
1254 memset(&opts
, 0, sizeof(opts
));
1255 opts
.add_title
= !have_message
;
1256 opts
.shortlog_len
= shortlog_len
;
1258 fmt_merge_msg(&merge_names
, &merge_msg
, &opts
);
1260 strbuf_setlen(&merge_msg
, merge_msg
.len
- 1);
1264 if (!head_commit
|| !argc
)
1265 usage_with_options(builtin_merge_usage
,
1266 builtin_merge_options
);
1268 strbuf_addstr(&buf
, "merge");
1269 for (i
= 0; i
< argc
; i
++)
1270 strbuf_addf(&buf
, " %s", argv
[i
]);
1271 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
1274 for (i
= 0; i
< argc
; i
++) {
1275 struct commit
*commit
= get_merge_parent(argv
[i
]);
1277 die(_("%s - not something we can merge"), argv
[i
]);
1278 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1279 strbuf_addf(&buf
, "GITHEAD_%s",
1280 sha1_to_hex(commit
->object
.sha1
));
1281 setenv(buf
.buf
, argv
[i
], 1);
1283 if (merge_remote_util(commit
) &&
1284 merge_remote_util(commit
)->obj
&&
1285 merge_remote_util(commit
)->obj
->type
== OBJ_TAG
) {
1287 allow_fast_forward
= 0;
1291 if (option_edit
< 0)
1292 option_edit
= default_edit_option();
1294 if (!use_strategies
) {
1295 if (!remoteheads
->next
)
1296 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
1298 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
1301 for (i
= 0; i
< use_strategies_nr
; i
++) {
1302 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
1303 allow_fast_forward
= 0;
1304 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
1308 if (!remoteheads
->next
)
1309 common
= get_merge_bases(head_commit
, remoteheads
->item
, 1);
1311 struct commit_list
*list
= remoteheads
;
1312 commit_list_insert(head_commit
, &list
);
1313 common
= get_octopus_merge_bases(list
);
1317 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head_commit
->object
.sha1
,
1318 NULL
, 0, DIE_ON_ERR
);
1321 ; /* No common ancestors found. We need a real merge. */
1322 else if (!remoteheads
->next
&& !common
->next
&&
1323 common
->item
== remoteheads
->item
) {
1325 * If head can reach all the merge then we are up to date.
1326 * but first the most common case of merging one remote.
1328 finish_up_to_date("Already up-to-date.");
1330 } else if (allow_fast_forward
&& !remoteheads
->next
&&
1332 !hashcmp(common
->item
->object
.sha1
, head_commit
->object
.sha1
)) {
1333 /* Again the most common case of merging one remote. */
1334 struct strbuf msg
= STRBUF_INIT
;
1335 struct commit
*commit
;
1338 strcpy(hex
, find_unique_abbrev(head_commit
->object
.sha1
, DEFAULT_ABBREV
));
1341 printf(_("Updating %s..%s\n"),
1343 find_unique_abbrev(remoteheads
->item
->object
.sha1
,
1345 strbuf_addstr(&msg
, "Fast-forward");
1348 " (no commit created; -m option ignored)");
1349 commit
= remoteheads
->item
;
1353 if (checkout_fast_forward(head_commit
->object
.sha1
,
1354 commit
->object
.sha1
))
1357 finish(head_commit
, commit
->object
.sha1
, msg
.buf
);
1360 } else if (!remoteheads
->next
&& common
->next
)
1363 * We are not doing octopus and not fast-forward. Need
1366 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1368 * We are not doing octopus, not fast-forward, and have
1371 refresh_cache(REFRESH_QUIET
);
1372 if (allow_trivial
&& !fast_forward_only
) {
1373 /* See if it is really trivial. */
1374 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1375 printf(_("Trying really trivial in-index merge...\n"));
1376 if (!read_tree_trivial(common
->item
->object
.sha1
,
1377 head_commit
->object
.sha1
, remoteheads
->item
->object
.sha1
))
1378 return merge_trivial(head_commit
);
1379 printf(_("Nope.\n"));
1383 * An octopus. If we can reach all the remote we are up
1387 struct commit_list
*j
;
1389 for (j
= remoteheads
; j
; j
= j
->next
) {
1390 struct commit_list
*common_one
;
1393 * Here we *have* to calculate the individual
1394 * merge_bases again, otherwise "git merge HEAD^
1395 * HEAD^^" would be missed.
1397 common_one
= get_merge_bases(head_commit
, j
->item
, 1);
1398 if (hashcmp(common_one
->item
->object
.sha1
,
1399 j
->item
->object
.sha1
)) {
1405 finish_up_to_date("Already up-to-date. Yeeah!");
1410 if (fast_forward_only
)
1411 die(_("Not possible to fast-forward, aborting."));
1413 /* We are going to make a new commit. */
1414 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1417 * At this point, we need a real merge. No matter what strategy
1418 * we use, it would operate on the index, possibly affecting the
1419 * working tree, and when resolved cleanly, have the desired
1420 * tree in the index -- this means that the index must be in
1421 * sync with the head commit. The strategies are responsible
1424 if (use_strategies_nr
== 1 ||
1426 * Stash away the local changes so that we can try more than one.
1429 hashcpy(stash
, null_sha1
);
1431 for (i
= 0; i
< use_strategies_nr
; i
++) {
1434 printf(_("Rewinding the tree to pristine...\n"));
1435 restore_state(head_commit
->object
.sha1
, stash
);
1437 if (use_strategies_nr
!= 1)
1438 printf(_("Trying merge strategy %s...\n"),
1439 use_strategies
[i
]->name
);
1441 * Remember which strategy left the state in the working
1444 wt_strategy
= use_strategies
[i
]->name
;
1446 ret
= try_merge_strategy(use_strategies
[i
]->name
,
1447 common
, head_commit
, head_arg
);
1448 if (!option_commit
&& !ret
) {
1451 * This is necessary here just to avoid writing
1452 * the tree, but later we will *not* exit with
1453 * status code 1 because merge_was_ok is set.
1460 * The backend exits with 1 when conflicts are
1461 * left to be resolved, with 2 when it does not
1462 * handle the given merge at all.
1465 int cnt
= evaluate_result();
1467 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1468 best_strategy
= use_strategies
[i
]->name
;
1478 /* Automerge succeeded. */
1479 write_tree_trivial(result_tree
);
1480 automerge_was_ok
= 1;
1485 * If we have a resulting tree, that means the strategy module
1486 * auto resolved the merge cleanly.
1488 if (automerge_was_ok
)
1489 return finish_automerge(head_commit
, common
, result_tree
,
1493 * Pick the result from the best strategy and have the user fix
1496 if (!best_strategy
) {
1497 restore_state(head_commit
->object
.sha1
, stash
);
1498 if (use_strategies_nr
> 1)
1500 _("No merge strategy handled the merge.\n"));
1502 fprintf(stderr
, _("Merge with strategy %s failed.\n"),
1503 use_strategies
[0]->name
);
1505 } else if (best_strategy
== wt_strategy
)
1506 ; /* We already have its result in the working tree. */
1508 printf(_("Rewinding the tree to pristine...\n"));
1509 restore_state(head_commit
->object
.sha1
, stash
);
1510 printf(_("Using the %s to prepare resolving by hand.\n"),
1512 try_merge_strategy(best_strategy
, common
, head_commit
, head_arg
);
1516 finish(head_commit
, NULL
, NULL
);
1518 write_merge_state();
1521 fprintf(stderr
, _("Automatic merge went well; "
1522 "stopped before committing as requested\n"));
1525 return suggest_conflicts(option_renormalize
);