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
;
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_BOOLEAN('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
;
319 const char *filename
;
321 struct pretty_print_context ctx
= {0};
323 printf(_("Squash commit -- not updating HEAD\n"));
324 filename
= git_path("SQUASH_MSG");
325 fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
327 die_errno(_("Could not write to '%s'"), filename
);
329 init_revisions(&rev
, NULL
);
330 rev
.ignore_merges
= 1;
331 rev
.commit_format
= CMIT_FMT_MEDIUM
;
333 commit
->object
.flags
|= UNINTERESTING
;
334 add_pending_object(&rev
, &commit
->object
, NULL
);
336 for (j
= remoteheads
; j
; j
= j
->next
)
337 add_pending_object(&rev
, &j
->item
->object
, NULL
);
339 setup_revisions(0, NULL
, &rev
, NULL
);
340 if (prepare_revision_walk(&rev
))
341 die(_("revision walk setup failed"));
343 ctx
.abbrev
= rev
.abbrev
;
344 ctx
.date_mode
= rev
.date_mode
;
345 ctx
.fmt
= rev
.commit_format
;
347 strbuf_addstr(&out
, "Squashed commit of the following:\n");
348 while ((commit
= get_revision(&rev
)) != NULL
) {
349 strbuf_addch(&out
, '\n');
350 strbuf_addf(&out
, "commit %s\n",
351 sha1_to_hex(commit
->object
.sha1
));
352 pretty_print_commit(&ctx
, commit
, &out
);
354 if (write(fd
, out
.buf
, out
.len
) < 0)
355 die_errno(_("Writing SQUASH_MSG"));
357 die_errno(_("Finishing SQUASH_MSG"));
358 strbuf_release(&out
);
361 static void finish(struct commit
*head_commit
,
362 const unsigned char *new_head
, const char *msg
)
364 struct strbuf reflog_message
= STRBUF_INIT
;
365 const unsigned char *head
= head_commit
->object
.sha1
;
368 strbuf_addstr(&reflog_message
, getenv("GIT_REFLOG_ACTION"));
372 strbuf_addf(&reflog_message
, "%s: %s",
373 getenv("GIT_REFLOG_ACTION"), msg
);
376 squash_message(head_commit
);
378 if (verbosity
>= 0 && !merge_msg
.len
)
379 printf(_("No merge message -- not updating HEAD\n"));
381 const char *argv_gc_auto
[] = { "gc", "--auto", NULL
};
382 update_ref(reflog_message
.buf
, "HEAD",
386 * We ignore errors in 'gc --auto', since the
387 * user should see them.
389 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
392 if (new_head
&& show_diffstat
) {
393 struct diff_options opts
;
395 opts
.output_format
|=
396 DIFF_FORMAT_SUMMARY
| DIFF_FORMAT_DIFFSTAT
;
397 opts
.detect_rename
= DIFF_DETECT_RENAME
;
398 if (diff_setup_done(&opts
) < 0)
399 die(_("diff_setup_done failed"));
400 diff_tree_sha1(head
, new_head
, "", &opts
);
405 /* Run a post-merge hook */
406 run_hook(NULL
, "post-merge", squash
? "1" : "0", NULL
);
408 strbuf_release(&reflog_message
);
411 static struct object
*want_commit(const char *name
)
414 unsigned char sha1
[20];
415 if (get_sha1(name
, sha1
))
417 obj
= parse_object(sha1
);
418 return peel_to_type(name
, 0, obj
, OBJ_COMMIT
);
421 /* Get the name for the merge commit's message. */
422 static void merge_name(const char *remote
, struct strbuf
*msg
)
424 struct object
*remote_head
;
425 unsigned char branch_head
[20], buf_sha
[20];
426 struct strbuf buf
= STRBUF_INIT
;
427 struct strbuf bname
= STRBUF_INIT
;
432 strbuf_branchname(&bname
, remote
);
435 memset(branch_head
, 0, sizeof(branch_head
));
436 remote_head
= want_commit(remote
);
438 die(_("'%s' does not point to a commit"), remote
);
440 if (dwim_ref(remote
, strlen(remote
), branch_head
, &found_ref
) > 0) {
441 if (!prefixcmp(found_ref
, "refs/heads/")) {
442 strbuf_addf(msg
, "%s\t\tbranch '%s' of .\n",
443 sha1_to_hex(branch_head
), remote
);
446 if (!prefixcmp(found_ref
, "refs/remotes/")) {
447 strbuf_addf(msg
, "%s\t\tremote-tracking branch '%s' of .\n",
448 sha1_to_hex(branch_head
), remote
);
453 /* See if remote matches <name>^^^.. or <name>~<number> */
454 for (len
= 0, ptr
= remote
+ strlen(remote
);
455 remote
< ptr
&& ptr
[-1] == '^';
462 ptr
= strrchr(remote
, '~');
464 int seen_nonzero
= 0;
467 while (*++ptr
&& isdigit(*ptr
)) {
468 seen_nonzero
|= (*ptr
!= '0');
472 len
= 0; /* not ...~<number> */
473 else if (seen_nonzero
)
476 early
= 1; /* "name~" is "name~1"! */
480 struct strbuf truname
= STRBUF_INIT
;
481 strbuf_addstr(&truname
, "refs/heads/");
482 strbuf_addstr(&truname
, remote
);
483 strbuf_setlen(&truname
, truname
.len
- len
);
484 if (resolve_ref(truname
.buf
, buf_sha
, 1, NULL
)) {
486 "%s\t\tbranch '%s'%s of .\n",
487 sha1_to_hex(remote_head
->sha1
),
489 (early
? " (early part)" : ""));
490 strbuf_release(&truname
);
495 if (!strcmp(remote
, "FETCH_HEAD") &&
496 !access(git_path("FETCH_HEAD"), R_OK
)) {
497 const char *filename
;
499 struct strbuf line
= STRBUF_INIT
;
502 filename
= git_path("FETCH_HEAD");
503 fp
= fopen(filename
, "r");
505 die_errno(_("could not open '%s' for reading"),
507 strbuf_getline(&line
, fp
, '\n');
509 ptr
= strstr(line
.buf
, "\tnot-for-merge\t");
511 strbuf_remove(&line
, ptr
-line
.buf
+1, 13);
512 strbuf_addbuf(msg
, &line
);
513 strbuf_release(&line
);
516 strbuf_addf(msg
, "%s\t\tcommit '%s'\n",
517 sha1_to_hex(remote_head
->sha1
), remote
);
519 strbuf_release(&buf
);
520 strbuf_release(&bname
);
523 static void parse_branch_merge_options(char *bmo
)
530 argc
= split_cmdline(bmo
, &argv
);
532 die(_("Bad branch.%s.mergeoptions string: %s"), branch
,
533 split_cmdline_strerror(argc
));
534 argv
= xrealloc(argv
, sizeof(*argv
) * (argc
+ 2));
535 memmove(argv
+ 1, argv
, sizeof(*argv
) * (argc
+ 1));
537 argv
[0] = "branch.*.mergeoptions";
538 parse_options(argc
, argv
, NULL
, builtin_merge_options
,
539 builtin_merge_usage
, 0);
543 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.log") || !strcmp(k
, "merge.summary")) {
563 shortlog_len
= git_config_bool_or_int(k
, v
, &is_bool
);
564 if (!is_bool
&& shortlog_len
< 0)
565 return error(_("%s: negative length %s"), k
, v
);
566 if (is_bool
&& shortlog_len
)
567 shortlog_len
= DEFAULT_MERGE_LOG_LEN
;
569 } else if (!strcmp(k
, "merge.ff")) {
570 int boolval
= git_config_maybe_bool(k
, v
);
572 allow_fast_forward
= boolval
;
573 } else if (v
&& !strcmp(v
, "only")) {
574 allow_fast_forward
= 1;
575 fast_forward_only
= 1;
576 } /* do not barf on values from future versions of git */
578 } else if (!strcmp(k
, "merge.defaulttoupstream")) {
579 default_to_upstream
= git_config_bool(k
, v
);
582 return git_diff_ui_config(k
, v
, cb
);
585 static int read_tree_trivial(unsigned char *common
, unsigned char *head
,
589 struct tree
*trees
[MAX_UNPACK_TREES
];
590 struct tree_desc t
[MAX_UNPACK_TREES
];
591 struct unpack_trees_options opts
;
593 memset(&opts
, 0, sizeof(opts
));
595 opts
.src_index
= &the_index
;
596 opts
.dst_index
= &the_index
;
598 opts
.verbose_update
= 1;
599 opts
.trivial_merges_only
= 1;
601 trees
[nr_trees
] = parse_tree_indirect(common
);
602 if (!trees
[nr_trees
++])
604 trees
[nr_trees
] = parse_tree_indirect(head
);
605 if (!trees
[nr_trees
++])
607 trees
[nr_trees
] = parse_tree_indirect(one
);
608 if (!trees
[nr_trees
++])
610 opts
.fn
= threeway_merge
;
611 cache_tree_free(&active_cache_tree
);
612 for (i
= 0; i
< nr_trees
; i
++) {
613 parse_tree(trees
[i
]);
614 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
616 if (unpack_trees(nr_trees
, t
, &opts
))
621 static void write_tree_trivial(unsigned char *sha1
)
623 if (write_cache_as_tree(sha1
, 0, NULL
))
624 die(_("git write-tree failed to write a tree"));
627 static const char *merge_argument(struct commit
*commit
)
630 return sha1_to_hex(commit
->object
.sha1
);
632 return EMPTY_TREE_SHA1_HEX
;
635 int try_merge_command(const char *strategy
, size_t xopts_nr
,
636 const char **xopts
, struct commit_list
*common
,
637 const char *head_arg
, struct commit_list
*remotes
)
640 int i
= 0, x
= 0, ret
;
641 struct commit_list
*j
;
642 struct strbuf buf
= STRBUF_INIT
;
644 args
= xmalloc((4 + xopts_nr
+ commit_list_count(common
) +
645 commit_list_count(remotes
)) * sizeof(char *));
646 strbuf_addf(&buf
, "merge-%s", strategy
);
648 for (x
= 0; x
< xopts_nr
; x
++) {
649 char *s
= xmalloc(strlen(xopts
[x
])+2+1);
651 strcpy(s
+2, xopts
[x
]);
654 for (j
= common
; j
; j
= j
->next
)
655 args
[i
++] = xstrdup(merge_argument(j
->item
));
657 args
[i
++] = head_arg
;
658 for (j
= remotes
; j
; j
= j
->next
)
659 args
[i
++] = xstrdup(merge_argument(j
->item
));
661 ret
= run_command_v_opt(args
, RUN_GIT_CMD
);
662 strbuf_release(&buf
);
664 for (x
= 0; x
< xopts_nr
; x
++)
665 free((void *)args
[i
++]);
666 for (j
= common
; j
; j
= j
->next
)
667 free((void *)args
[i
++]);
669 for (j
= remotes
; j
; j
= j
->next
)
670 free((void *)args
[i
++]);
673 if (read_cache() < 0)
674 die(_("failed to read the cache"));
675 resolve_undo_clear();
680 static int try_merge_strategy(const char *strategy
, struct commit_list
*common
,
681 struct commit
*head
, const char *head_arg
)
684 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
686 index_fd
= hold_locked_index(lock
, 1);
687 refresh_cache(REFRESH_QUIET
);
688 if (active_cache_changed
&&
689 (write_cache(index_fd
, active_cache
, active_nr
) ||
690 commit_locked_index(lock
)))
691 return error(_("Unable to write index."));
692 rollback_lock_file(lock
);
694 if (!strcmp(strategy
, "recursive") || !strcmp(strategy
, "subtree")) {
696 struct commit
*result
;
697 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
699 struct commit_list
*reversed
= NULL
;
700 struct merge_options o
;
701 struct commit_list
*j
;
703 if (remoteheads
->next
) {
704 error(_("Not handling anything other than two heads merge."));
708 init_merge_options(&o
);
709 if (!strcmp(strategy
, "subtree"))
710 o
.subtree_shift
= "";
712 o
.renormalize
= option_renormalize
;
713 o
.show_rename_progress
=
714 show_progress
== -1 ? isatty(2) : show_progress
;
716 for (x
= 0; x
< xopts_nr
; x
++)
717 if (parse_merge_opt(&o
, xopts
[x
]))
718 die(_("Unknown option for merge-recursive: -X%s"), xopts
[x
]);
720 o
.branch1
= head_arg
;
721 o
.branch2
= remoteheads
->item
->util
;
723 for (j
= common
; j
; j
= j
->next
)
724 commit_list_insert(j
->item
, &reversed
);
726 index_fd
= hold_locked_index(lock
, 1);
727 clean
= merge_recursive(&o
, head
,
728 remoteheads
->item
, reversed
, &result
);
729 if (active_cache_changed
&&
730 (write_cache(index_fd
, active_cache
, active_nr
) ||
731 commit_locked_index(lock
)))
732 die (_("unable to write %s"), get_index_file());
733 rollback_lock_file(lock
);
734 return clean
? 0 : 1;
736 return try_merge_command(strategy
, xopts_nr
, xopts
,
737 common
, head_arg
, remoteheads
);
741 static void count_diff_files(struct diff_queue_struct
*q
,
742 struct diff_options
*opt
, void *data
)
749 static int count_unmerged_entries(void)
753 for (i
= 0; i
< active_nr
; i
++)
754 if (ce_stage(active_cache
[i
]))
760 int checkout_fast_forward(const unsigned char *head
, const unsigned char *remote
)
762 struct tree
*trees
[MAX_UNPACK_TREES
];
763 struct unpack_trees_options opts
;
764 struct tree_desc t
[MAX_UNPACK_TREES
];
765 int i
, fd
, nr_trees
= 0;
766 struct dir_struct dir
;
767 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
769 refresh_cache(REFRESH_QUIET
);
771 fd
= hold_locked_index(lock_file
, 1);
773 memset(&trees
, 0, sizeof(trees
));
774 memset(&opts
, 0, sizeof(opts
));
775 memset(&t
, 0, sizeof(t
));
776 memset(&dir
, 0, sizeof(dir
));
777 dir
.flags
|= DIR_SHOW_IGNORED
;
778 setup_standard_excludes(&dir
);
782 opts
.src_index
= &the_index
;
783 opts
.dst_index
= &the_index
;
785 opts
.verbose_update
= 1;
787 opts
.fn
= twoway_merge
;
788 setup_unpack_trees_porcelain(&opts
, "merge");
790 trees
[nr_trees
] = parse_tree_indirect(head
);
791 if (!trees
[nr_trees
++])
793 trees
[nr_trees
] = parse_tree_indirect(remote
);
794 if (!trees
[nr_trees
++])
796 for (i
= 0; i
< nr_trees
; i
++) {
797 parse_tree(trees
[i
]);
798 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
800 if (unpack_trees(nr_trees
, t
, &opts
))
802 if (write_cache(fd
, active_cache
, active_nr
) ||
803 commit_locked_index(lock_file
))
804 die(_("unable to write new index file"));
808 static void split_merge_strategies(const char *string
, struct strategy
**list
,
816 buf
= xstrdup(string
);
821 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
822 (*list
)[(*nr
)++].name
= xstrdup(q
);
827 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
828 (*list
)[(*nr
)++].name
= xstrdup(q
);
834 static void add_strategies(const char *string
, unsigned attr
)
836 struct strategy
*list
= NULL
;
837 int list_alloc
= 0, list_nr
= 0, i
;
839 memset(&list
, 0, sizeof(list
));
840 split_merge_strategies(string
, &list
, &list_nr
, &list_alloc
);
842 for (i
= 0; i
< list_nr
; i
++)
843 append_strategy(get_strategy(list
[i
].name
));
846 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
847 if (all_strategy
[i
].attr
& attr
)
848 append_strategy(&all_strategy
[i
]);
852 static void write_merge_msg(struct strbuf
*msg
)
854 const char *filename
= git_path("MERGE_MSG");
855 int fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
857 die_errno(_("Could not open '%s' for writing"),
859 if (write_in_full(fd
, msg
->buf
, msg
->len
) != msg
->len
)
860 die_errno(_("Could not write to '%s'"), filename
);
864 static void read_merge_msg(struct strbuf
*msg
)
866 const char *filename
= git_path("MERGE_MSG");
868 if (strbuf_read_file(msg
, filename
, 0) < 0)
869 die_errno(_("Could not read from '%s'"), filename
);
872 static void write_merge_state(void);
873 static void abort_commit(const char *err_msg
)
876 error("%s", err_msg
);
878 _("Not committing merge; use 'git commit' to complete the merge.\n"));
883 static void prepare_to_commit(void)
885 struct strbuf msg
= STRBUF_INIT
;
886 strbuf_addbuf(&msg
, &merge_msg
);
887 strbuf_addch(&msg
, '\n');
888 write_merge_msg(&msg
);
889 run_hook(get_index_file(), "prepare-commit-msg",
890 git_path("MERGE_MSG"), "merge", NULL
, NULL
);
892 if (launch_editor(git_path("MERGE_MSG"), NULL
, NULL
))
895 read_merge_msg(&msg
);
896 stripspace(&msg
, option_edit
);
898 abort_commit(_("Empty commit message."));
899 strbuf_release(&merge_msg
);
900 strbuf_addbuf(&merge_msg
, &msg
);
901 strbuf_release(&msg
);
904 static int merge_trivial(struct commit
*head
)
906 unsigned char result_tree
[20], result_commit
[20];
907 struct commit_list
*parent
= xmalloc(sizeof(*parent
));
909 write_tree_trivial(result_tree
);
910 printf(_("Wonderful.\n"));
912 parent
->next
= xmalloc(sizeof(*parent
->next
));
913 parent
->next
->item
= remoteheads
->item
;
914 parent
->next
->next
= NULL
;
916 commit_tree(merge_msg
.buf
, result_tree
, parent
, result_commit
, NULL
);
917 finish(head
, result_commit
, "In-index merge");
922 static int finish_automerge(struct commit
*head
,
923 struct commit_list
*common
,
924 unsigned char *result_tree
,
925 const char *wt_strategy
)
927 struct commit_list
*parents
= NULL
, *j
;
928 struct strbuf buf
= STRBUF_INIT
;
929 unsigned char result_commit
[20];
931 free_commit_list(common
);
932 if (allow_fast_forward
) {
933 parents
= remoteheads
;
934 commit_list_insert(head
, &parents
);
935 parents
= reduce_heads(parents
);
937 struct commit_list
**pptr
= &parents
;
939 pptr
= &commit_list_insert(head
,
941 for (j
= remoteheads
; j
; j
= j
->next
)
942 pptr
= &commit_list_insert(j
->item
, pptr
)->next
;
944 strbuf_addch(&merge_msg
, '\n');
946 free_commit_list(remoteheads
);
947 commit_tree(merge_msg
.buf
, result_tree
, parents
, result_commit
, NULL
);
948 strbuf_addf(&buf
, "Merge made by the '%s' strategy.", wt_strategy
);
949 finish(head
, result_commit
, buf
.buf
);
950 strbuf_release(&buf
);
955 static int suggest_conflicts(int renormalizing
)
957 const char *filename
;
961 filename
= git_path("MERGE_MSG");
962 fp
= fopen(filename
, "a");
964 die_errno(_("Could not open '%s' for writing"), filename
);
965 fprintf(fp
, "\nConflicts:\n");
966 for (pos
= 0; pos
< active_nr
; pos
++) {
967 struct cache_entry
*ce
= active_cache
[pos
];
970 fprintf(fp
, "\t%s\n", ce
->name
);
971 while (pos
+ 1 < active_nr
&&
973 active_cache
[pos
+ 1]->name
))
978 rerere(allow_rerere_auto
);
979 printf(_("Automatic merge failed; "
980 "fix conflicts and then commit the result.\n"));
984 static struct commit
*is_old_style_invocation(int argc
, const char **argv
,
985 const unsigned char *head
)
987 struct commit
*second_token
= NULL
;
989 unsigned char second_sha1
[20];
991 if (get_sha1(argv
[1], second_sha1
))
993 second_token
= lookup_commit_reference_gently(second_sha1
, 0);
995 die(_("'%s' is not a commit"), argv
[1]);
996 if (hashcmp(second_token
->object
.sha1
, head
))
1002 static int evaluate_result(void)
1005 struct rev_info rev
;
1007 /* Check how many files differ. */
1008 init_revisions(&rev
, "");
1009 setup_revisions(0, NULL
, &rev
, NULL
);
1010 rev
.diffopt
.output_format
|=
1011 DIFF_FORMAT_CALLBACK
;
1012 rev
.diffopt
.format_callback
= count_diff_files
;
1013 rev
.diffopt
.format_callback_data
= &cnt
;
1014 run_diff_files(&rev
, 0);
1017 * Check how many unmerged entries are
1020 cnt
+= count_unmerged_entries();
1026 * Pretend as if the user told us to merge with the tracking
1027 * branch we have for the upstream of the current branch
1029 static int setup_with_upstream(const char ***argv
)
1031 struct branch
*branch
= branch_get(NULL
);
1036 die(_("No current branch."));
1037 if (!branch
->remote
)
1038 die(_("No remote for the current branch."));
1039 if (!branch
->merge_nr
)
1040 die(_("No default upstream defined for the current branch."));
1042 args
= xcalloc(branch
->merge_nr
+ 1, sizeof(char *));
1043 for (i
= 0; i
< branch
->merge_nr
; i
++) {
1044 if (!branch
->merge
[i
]->dst
)
1045 die(_("No remote tracking branch for %s from %s"),
1046 branch
->merge
[i
]->src
, branch
->remote_name
);
1047 args
[i
] = branch
->merge
[i
]->dst
;
1054 static void write_merge_state(void)
1056 const char *filename
;
1058 struct commit_list
*j
;
1059 struct strbuf buf
= STRBUF_INIT
;
1061 for (j
= remoteheads
; j
; j
= j
->next
)
1062 strbuf_addf(&buf
, "%s\n",
1063 sha1_to_hex(j
->item
->object
.sha1
));
1064 filename
= git_path("MERGE_HEAD");
1065 fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
1067 die_errno(_("Could not open '%s' for writing"), filename
);
1068 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1069 die_errno(_("Could not write to '%s'"), filename
);
1071 strbuf_addch(&merge_msg
, '\n');
1072 write_merge_msg(&merge_msg
);
1074 filename
= git_path("MERGE_MODE");
1075 fd
= open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
1077 die_errno(_("Could not open '%s' for writing"), filename
);
1079 if (!allow_fast_forward
)
1080 strbuf_addf(&buf
, "no-ff");
1081 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1082 die_errno(_("Could not write to '%s'"), filename
);
1086 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
1088 unsigned char result_tree
[20];
1089 unsigned char stash
[20];
1090 unsigned char head_sha1
[20];
1091 struct commit
*head_commit
;
1092 struct strbuf buf
= STRBUF_INIT
;
1093 const char *head_arg
;
1095 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
1096 struct commit_list
*common
= NULL
;
1097 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
1098 struct commit_list
**remotes
= &remoteheads
;
1100 if (argc
== 2 && !strcmp(argv
[1], "-h"))
1101 usage_with_options(builtin_merge_usage
, builtin_merge_options
);
1104 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1107 branch
= resolve_ref("HEAD", head_sha1
, 0, &flag
);
1108 if (branch
&& !prefixcmp(branch
, "refs/heads/"))
1110 if (!branch
|| is_null_sha1(head_sha1
))
1113 head_commit
= lookup_commit_or_die(head_sha1
, "HEAD");
1115 git_config(git_merge_config
, NULL
);
1117 if (branch_mergeoptions
)
1118 parse_branch_merge_options(branch_mergeoptions
);
1119 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
1120 builtin_merge_usage
, 0);
1122 if (verbosity
< 0 && show_progress
== -1)
1125 if (abort_current_merge
) {
1127 const char *nargv
[] = {"reset", "--merge", NULL
};
1129 if (!file_exists(git_path("MERGE_HEAD")))
1130 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1132 /* Invoke 'git reset --merge' */
1133 return cmd_reset(nargc
, nargv
, prefix
);
1136 if (read_cache_unmerged())
1137 die_resolve_conflict("merge");
1139 if (file_exists(git_path("MERGE_HEAD"))) {
1141 * There is no unmerged entry, don't advise 'git
1142 * add/rm <file>', just 'git commit'.
1144 if (advice_resolve_conflict
)
1145 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1146 "Please, commit your changes before you can merge."));
1148 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1150 if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
1151 if (advice_resolve_conflict
)
1152 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1153 "Please, commit your changes before you can merge."));
1155 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1157 resolve_undo_clear();
1163 if (!allow_fast_forward
)
1164 die(_("You cannot combine --squash with --no-ff."));
1168 if (!allow_fast_forward
&& fast_forward_only
)
1169 die(_("You cannot combine --no-ff with --ff-only."));
1171 if (!abort_current_merge
) {
1172 if (!argc
&& default_to_upstream
)
1173 argc
= setup_with_upstream(&argv
);
1174 else if (argc
== 1 && !strcmp(argv
[0], "-"))
1178 usage_with_options(builtin_merge_usage
,
1179 builtin_merge_options
);
1182 * This could be traditional "merge <msg> HEAD <commit>..." and
1183 * the way we can tell it is to see if the second token is HEAD,
1184 * but some people might have misused the interface and used a
1185 * committish that is the same as HEAD there instead.
1186 * Traditional format never would have "-m" so it is an
1187 * additional safety measure to check for it.
1190 if (!have_message
&& head_commit
&&
1191 is_old_style_invocation(argc
, argv
, head_commit
->object
.sha1
)) {
1192 strbuf_addstr(&merge_msg
, argv
[0]);
1196 } else if (!head_commit
) {
1197 struct object
*remote_head
;
1199 * If the merged head is a valid one there is no reason
1200 * to forbid "git merge" into a branch yet to be born.
1201 * We do the same for "git pull".
1204 die(_("Can merge only exactly one commit into "
1207 die(_("Squash commit into empty head not supported yet"));
1208 if (!allow_fast_forward
)
1209 die(_("Non-fast-forward commit does not make sense into "
1211 remote_head
= want_commit(argv
[0]);
1213 die(_("%s - not something we can merge"), argv
[0]);
1214 read_empty(remote_head
->sha1
, 0);
1215 update_ref("initial pull", "HEAD", remote_head
->sha1
, NULL
, 0,
1219 struct strbuf merge_names
= STRBUF_INIT
;
1221 /* We are invoked directly as the first-class UI. */
1225 * All the rest are the commits being merged;
1226 * prepare the standard merge summary message to
1227 * be appended to the given message. If remote
1228 * is invalid we will die later in the common
1229 * codepath so we discard the error in this
1232 for (i
= 0; i
< argc
; i
++)
1233 merge_name(argv
[i
], &merge_names
);
1235 if (!have_message
|| shortlog_len
) {
1236 fmt_merge_msg(&merge_names
, &merge_msg
, !have_message
,
1239 strbuf_setlen(&merge_msg
, merge_msg
.len
- 1);
1243 if (!head_commit
|| !argc
)
1244 usage_with_options(builtin_merge_usage
,
1245 builtin_merge_options
);
1247 strbuf_addstr(&buf
, "merge");
1248 for (i
= 0; i
< argc
; i
++)
1249 strbuf_addf(&buf
, " %s", argv
[i
]);
1250 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
1253 for (i
= 0; i
< argc
; i
++) {
1255 struct commit
*commit
;
1257 o
= want_commit(argv
[i
]);
1259 die(_("%s - not something we can merge"), argv
[i
]);
1260 commit
= lookup_commit(o
->sha1
);
1261 commit
->util
= (void *)argv
[i
];
1262 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1264 strbuf_addf(&buf
, "GITHEAD_%s", sha1_to_hex(o
->sha1
));
1265 setenv(buf
.buf
, argv
[i
], 1);
1269 if (!use_strategies
) {
1270 if (!remoteheads
->next
)
1271 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
1273 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
1276 for (i
= 0; i
< use_strategies_nr
; i
++) {
1277 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
1278 allow_fast_forward
= 0;
1279 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
1283 if (!remoteheads
->next
)
1284 common
= get_merge_bases(head_commit
, remoteheads
->item
, 1);
1286 struct commit_list
*list
= remoteheads
;
1287 commit_list_insert(head_commit
, &list
);
1288 common
= get_octopus_merge_bases(list
);
1292 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head_commit
->object
.sha1
,
1293 NULL
, 0, DIE_ON_ERR
);
1296 ; /* No common ancestors found. We need a real merge. */
1297 else if (!remoteheads
->next
&& !common
->next
&&
1298 common
->item
== remoteheads
->item
) {
1300 * If head can reach all the merge then we are up to date.
1301 * but first the most common case of merging one remote.
1303 finish_up_to_date("Already up-to-date.");
1305 } else if (allow_fast_forward
&& !remoteheads
->next
&&
1307 !hashcmp(common
->item
->object
.sha1
, head_commit
->object
.sha1
)) {
1308 /* Again the most common case of merging one remote. */
1309 struct strbuf msg
= STRBUF_INIT
;
1313 strcpy(hex
, find_unique_abbrev(head_commit
->object
.sha1
, DEFAULT_ABBREV
));
1316 printf(_("Updating %s..%s\n"),
1318 find_unique_abbrev(remoteheads
->item
->object
.sha1
,
1320 strbuf_addstr(&msg
, "Fast-forward");
1323 " (no commit created; -m option ignored)");
1324 o
= want_commit(sha1_to_hex(remoteheads
->item
->object
.sha1
));
1328 if (checkout_fast_forward(head_commit
->object
.sha1
, remoteheads
->item
->object
.sha1
))
1331 finish(head_commit
, o
->sha1
, msg
.buf
);
1334 } else if (!remoteheads
->next
&& common
->next
)
1337 * We are not doing octopus and not fast-forward. Need
1340 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1342 * We are not doing octopus, not fast-forward, and have
1345 refresh_cache(REFRESH_QUIET
);
1346 if (allow_trivial
&& !fast_forward_only
) {
1347 /* See if it is really trivial. */
1348 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1349 printf(_("Trying really trivial in-index merge...\n"));
1350 if (!read_tree_trivial(common
->item
->object
.sha1
,
1351 head_commit
->object
.sha1
, remoteheads
->item
->object
.sha1
))
1352 return merge_trivial(head_commit
);
1353 printf(_("Nope.\n"));
1357 * An octopus. If we can reach all the remote we are up
1361 struct commit_list
*j
;
1363 for (j
= remoteheads
; j
; j
= j
->next
) {
1364 struct commit_list
*common_one
;
1367 * Here we *have* to calculate the individual
1368 * merge_bases again, otherwise "git merge HEAD^
1369 * HEAD^^" would be missed.
1371 common_one
= get_merge_bases(head_commit
, j
->item
, 1);
1372 if (hashcmp(common_one
->item
->object
.sha1
,
1373 j
->item
->object
.sha1
)) {
1379 finish_up_to_date("Already up-to-date. Yeeah!");
1384 if (fast_forward_only
)
1385 die(_("Not possible to fast-forward, aborting."));
1387 /* We are going to make a new commit. */
1388 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1391 * At this point, we need a real merge. No matter what strategy
1392 * we use, it would operate on the index, possibly affecting the
1393 * working tree, and when resolved cleanly, have the desired
1394 * tree in the index -- this means that the index must be in
1395 * sync with the head commit. The strategies are responsible
1398 if (use_strategies_nr
== 1 ||
1400 * Stash away the local changes so that we can try more than one.
1403 hashcpy(stash
, null_sha1
);
1405 for (i
= 0; i
< use_strategies_nr
; i
++) {
1408 printf(_("Rewinding the tree to pristine...\n"));
1409 restore_state(head_commit
->object
.sha1
, stash
);
1411 if (use_strategies_nr
!= 1)
1412 printf(_("Trying merge strategy %s...\n"),
1413 use_strategies
[i
]->name
);
1415 * Remember which strategy left the state in the working
1418 wt_strategy
= use_strategies
[i
]->name
;
1420 ret
= try_merge_strategy(use_strategies
[i
]->name
,
1421 common
, head_commit
, head_arg
);
1422 if (!option_commit
&& !ret
) {
1425 * This is necessary here just to avoid writing
1426 * the tree, but later we will *not* exit with
1427 * status code 1 because merge_was_ok is set.
1434 * The backend exits with 1 when conflicts are
1435 * left to be resolved, with 2 when it does not
1436 * handle the given merge at all.
1439 int cnt
= evaluate_result();
1441 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1442 best_strategy
= use_strategies
[i
]->name
;
1452 /* Automerge succeeded. */
1453 write_tree_trivial(result_tree
);
1454 automerge_was_ok
= 1;
1459 * If we have a resulting tree, that means the strategy module
1460 * auto resolved the merge cleanly.
1462 if (automerge_was_ok
)
1463 return finish_automerge(head_commit
, common
, result_tree
,
1467 * Pick the result from the best strategy and have the user fix
1470 if (!best_strategy
) {
1471 restore_state(head_commit
->object
.sha1
, stash
);
1472 if (use_strategies_nr
> 1)
1474 _("No merge strategy handled the merge.\n"));
1476 fprintf(stderr
, _("Merge with strategy %s failed.\n"),
1477 use_strategies
[0]->name
);
1479 } else if (best_strategy
== wt_strategy
)
1480 ; /* We already have its result in the working tree. */
1482 printf(_("Rewinding the tree to pristine...\n"));
1483 restore_state(head_commit
->object
.sha1
, stash
);
1484 printf(_("Using the %s to prepare resolving by hand.\n"),
1486 try_merge_strategy(best_strategy
, common
, head_commit
, head_arg
);
1490 finish(head_commit
, NULL
, NULL
);
1492 write_merge_state();
1495 fprintf(stderr
, _("Automatic merge went well; "
1496 "stopped before committing as requested\n"));
1499 return suggest_conflicts(option_renormalize
);