4 * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
6 * Based on git-merge.sh by Junio C Hamano.
10 #include "parse-options.h"
12 #include "run-command.h"
18 #include "unpack-trees.h"
19 #include "cache-tree.h"
26 #include "merge-recursive.h"
27 #include "resolve-undo.h"
29 #define DEFAULT_TWOHEAD (1<<0)
30 #define DEFAULT_OCTOPUS (1<<1)
31 #define NO_FAST_FORWARD (1<<2)
32 #define NO_TRIVIAL (1<<3)
39 static const char * const builtin_merge_usage
[] = {
40 "git merge [options] <remote>...",
41 "git merge [options] <msg> HEAD <remote>",
45 static int show_diffstat
= 1, option_log
, squash
;
46 static int option_commit
= 1, allow_fast_forward
= 1;
47 static int fast_forward_only
;
48 static int allow_trivial
= 1, have_message
;
49 static struct strbuf merge_msg
;
50 static struct commit_list
*remoteheads
;
51 static unsigned char head
[20], stash
[20];
52 static struct strategy
**use_strategies
;
53 static size_t use_strategies_nr
, use_strategies_alloc
;
54 static const char **xopts
;
55 static size_t xopts_nr
, xopts_alloc
;
56 static const char *branch
;
58 static int allow_rerere_auto
;
60 static struct strategy all_strategy
[] = {
61 { "recursive", DEFAULT_TWOHEAD
| NO_TRIVIAL
},
62 { "octopus", DEFAULT_OCTOPUS
},
64 { "ours", NO_FAST_FORWARD
| NO_TRIVIAL
},
65 { "subtree", NO_FAST_FORWARD
| NO_TRIVIAL
},
68 static const char *pull_twohead
, *pull_octopus
;
70 static int option_parse_message(const struct option
*opt
,
71 const char *arg
, int unset
)
73 struct strbuf
*buf
= opt
->value
;
76 strbuf_setlen(buf
, 0);
78 strbuf_addf(buf
, "%s%s", buf
->len
? "\n\n" : "", arg
);
81 return error("switch `m' requires a value");
85 static struct strategy
*get_strategy(const char *name
)
89 static struct cmdnames main_cmds
, other_cmds
;
95 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
96 if (!strcmp(name
, all_strategy
[i
].name
))
97 return &all_strategy
[i
];
100 struct cmdnames not_strategies
;
103 memset(¬_strategies
, 0, sizeof(struct cmdnames
));
104 load_command_list("git-merge-", &main_cmds
, &other_cmds
);
105 for (i
= 0; i
< main_cmds
.cnt
; i
++) {
107 struct cmdname
*ent
= main_cmds
.names
[i
];
108 for (j
= 0; j
< ARRAY_SIZE(all_strategy
); j
++)
109 if (!strncmp(ent
->name
, all_strategy
[j
].name
, ent
->len
)
110 && !all_strategy
[j
].name
[ent
->len
])
113 add_cmdname(¬_strategies
, ent
->name
, ent
->len
);
115 exclude_cmds(&main_cmds
, ¬_strategies
);
117 if (!is_in_cmdlist(&main_cmds
, name
) && !is_in_cmdlist(&other_cmds
, name
)) {
118 fprintf(stderr
, "Could not find merge strategy '%s'.\n", name
);
119 fprintf(stderr
, "Available strategies are:");
120 for (i
= 0; i
< main_cmds
.cnt
; i
++)
121 fprintf(stderr
, " %s", main_cmds
.names
[i
]->name
);
122 fprintf(stderr
, ".\n");
123 if (other_cmds
.cnt
) {
124 fprintf(stderr
, "Available custom strategies are:");
125 for (i
= 0; i
< other_cmds
.cnt
; i
++)
126 fprintf(stderr
, " %s", other_cmds
.names
[i
]->name
);
127 fprintf(stderr
, ".\n");
132 ret
= xcalloc(1, sizeof(struct strategy
));
133 ret
->name
= xstrdup(name
);
137 static void append_strategy(struct strategy
*s
)
139 ALLOC_GROW(use_strategies
, use_strategies_nr
+ 1, use_strategies_alloc
);
140 use_strategies
[use_strategies_nr
++] = s
;
143 static int option_parse_strategy(const struct option
*opt
,
144 const char *name
, int unset
)
149 append_strategy(get_strategy(name
));
153 static int option_parse_x(const struct option
*opt
,
154 const char *arg
, int unset
)
159 ALLOC_GROW(xopts
, xopts_nr
+ 1, xopts_alloc
);
160 xopts
[xopts_nr
++] = xstrdup(arg
);
164 static int option_parse_n(const struct option
*opt
,
165 const char *arg
, int unset
)
167 show_diffstat
= unset
;
171 static struct option builtin_merge_options
[] = {
172 { OPTION_CALLBACK
, 'n', NULL
, NULL
, NULL
,
173 "do not show a diffstat at the end of the merge",
174 PARSE_OPT_NOARG
, option_parse_n
},
175 OPT_BOOLEAN(0, "stat", &show_diffstat
,
176 "show a diffstat at the end of the merge"),
177 OPT_BOOLEAN(0, "summary", &show_diffstat
, "(synonym to --stat)"),
178 OPT_BOOLEAN(0, "log", &option_log
,
179 "add list of one-line log to merge commit message"),
180 OPT_BOOLEAN(0, "squash", &squash
,
181 "create a single commit instead of doing a merge"),
182 OPT_BOOLEAN(0, "commit", &option_commit
,
183 "perform a commit if the merge succeeds (default)"),
184 OPT_BOOLEAN(0, "ff", &allow_fast_forward
,
185 "allow fast-forward (default)"),
186 OPT_BOOLEAN(0, "ff-only", &fast_forward_only
,
187 "abort if fast-forward is not possible"),
188 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto
),
189 OPT_CALLBACK('s', "strategy", &use_strategies
, "strategy",
190 "merge strategy to use", option_parse_strategy
),
191 OPT_CALLBACK('X', "strategy-option", &xopts
, "option=value",
192 "option for selected merge strategy", option_parse_x
),
193 OPT_CALLBACK('m', "message", &merge_msg
, "message",
194 "message to be used for the merge commit (if any)",
195 option_parse_message
),
196 OPT__VERBOSITY(&verbosity
),
200 /* Cleans up metadata that is uninteresting after a succeeded merge. */
201 static void drop_save(void)
203 unlink(git_path("MERGE_HEAD"));
204 unlink(git_path("MERGE_MSG"));
205 unlink(git_path("MERGE_MODE"));
208 static void save_state(void)
211 struct child_process cp
;
212 struct strbuf buffer
= STRBUF_INIT
;
213 const char *argv
[] = {"stash", "create", NULL
};
215 memset(&cp
, 0, sizeof(cp
));
220 if (start_command(&cp
))
221 die("could not run stash.");
222 len
= strbuf_read(&buffer
, cp
.out
, 1024);
225 if (finish_command(&cp
) || len
< 0)
229 strbuf_setlen(&buffer
, buffer
.len
-1);
230 if (get_sha1(buffer
.buf
, stash
))
231 die("not a valid object: %s", buffer
.buf
);
234 static void reset_hard(unsigned const char *sha1
, int verbose
)
239 args
[i
++] = "read-tree";
242 args
[i
++] = "--reset";
244 args
[i
++] = sha1_to_hex(sha1
);
247 if (run_command_v_opt(args
, RUN_GIT_CMD
))
248 die("read-tree failed");
251 static void restore_state(void)
253 struct strbuf sb
= STRBUF_INIT
;
254 const char *args
[] = { "stash", "apply", NULL
, NULL
};
256 if (is_null_sha1(stash
))
261 args
[2] = sha1_to_hex(stash
);
264 * It is OK to ignore error here, for example when there was
265 * nothing to restore.
267 run_command_v_opt(args
, RUN_GIT_CMD
);
270 refresh_cache(REFRESH_QUIET
);
273 /* This is called when no merge was necessary. */
274 static void finish_up_to_date(const char *msg
)
277 printf("%s%s\n", squash
? " (nothing to squash)" : "", msg
);
281 static void squash_message(void)
284 struct commit
*commit
;
285 struct strbuf out
= STRBUF_INIT
;
286 struct commit_list
*j
;
288 struct pretty_print_context ctx
= {0};
290 printf("Squash commit -- not updating HEAD\n");
291 fd
= open(git_path("SQUASH_MSG"), O_WRONLY
| O_CREAT
, 0666);
293 die_errno("Could not write to '%s'", git_path("SQUASH_MSG"));
295 init_revisions(&rev
, NULL
);
296 rev
.ignore_merges
= 1;
297 rev
.commit_format
= CMIT_FMT_MEDIUM
;
299 commit
= lookup_commit(head
);
300 commit
->object
.flags
|= UNINTERESTING
;
301 add_pending_object(&rev
, &commit
->object
, NULL
);
303 for (j
= remoteheads
; j
; j
= j
->next
)
304 add_pending_object(&rev
, &j
->item
->object
, NULL
);
306 setup_revisions(0, NULL
, &rev
, NULL
);
307 if (prepare_revision_walk(&rev
))
308 die("revision walk setup failed");
310 ctx
.abbrev
= rev
.abbrev
;
311 ctx
.date_mode
= rev
.date_mode
;
313 strbuf_addstr(&out
, "Squashed commit of the following:\n");
314 while ((commit
= get_revision(&rev
)) != NULL
) {
315 strbuf_addch(&out
, '\n');
316 strbuf_addf(&out
, "commit %s\n",
317 sha1_to_hex(commit
->object
.sha1
));
318 pretty_print_commit(rev
.commit_format
, commit
, &out
, &ctx
);
320 if (write(fd
, out
.buf
, out
.len
) < 0)
321 die_errno("Writing SQUASH_MSG");
323 die_errno("Finishing SQUASH_MSG");
324 strbuf_release(&out
);
327 static void finish(const unsigned char *new_head
, const char *msg
)
329 struct strbuf reflog_message
= STRBUF_INIT
;
332 strbuf_addstr(&reflog_message
, getenv("GIT_REFLOG_ACTION"));
336 strbuf_addf(&reflog_message
, "%s: %s",
337 getenv("GIT_REFLOG_ACTION"), msg
);
342 if (verbosity
>= 0 && !merge_msg
.len
)
343 printf("No merge message -- not updating HEAD\n");
345 const char *argv_gc_auto
[] = { "gc", "--auto", NULL
};
346 update_ref(reflog_message
.buf
, "HEAD",
350 * We ignore errors in 'gc --auto', since the
351 * user should see them.
353 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
356 if (new_head
&& show_diffstat
) {
357 struct diff_options opts
;
359 opts
.output_format
|=
360 DIFF_FORMAT_SUMMARY
| DIFF_FORMAT_DIFFSTAT
;
361 opts
.detect_rename
= DIFF_DETECT_RENAME
;
362 if (diff_use_color_default
> 0)
363 DIFF_OPT_SET(&opts
, COLOR_DIFF
);
364 if (diff_setup_done(&opts
) < 0)
365 die("diff_setup_done failed");
366 diff_tree_sha1(head
, new_head
, "", &opts
);
371 /* Run a post-merge hook */
372 run_hook(NULL
, "post-merge", squash
? "1" : "0", NULL
);
374 strbuf_release(&reflog_message
);
377 /* Get the name for the merge commit's message. */
378 static void merge_name(const char *remote
, struct strbuf
*msg
)
380 struct object
*remote_head
;
381 unsigned char branch_head
[20], buf_sha
[20];
382 struct strbuf buf
= STRBUF_INIT
;
383 struct strbuf bname
= STRBUF_INIT
;
388 strbuf_branchname(&bname
, remote
);
391 memset(branch_head
, 0, sizeof(branch_head
));
392 remote_head
= peel_to_type(remote
, 0, NULL
, OBJ_COMMIT
);
394 die("'%s' does not point to a commit", remote
);
396 if (dwim_ref(remote
, strlen(remote
), branch_head
, &found_ref
) > 0) {
397 if (!prefixcmp(found_ref
, "refs/heads/")) {
398 strbuf_addf(msg
, "%s\t\tbranch '%s' of .\n",
399 sha1_to_hex(branch_head
), remote
);
402 if (!prefixcmp(found_ref
, "refs/remotes/")) {
403 strbuf_addf(msg
, "%s\t\tremote branch '%s' of .\n",
404 sha1_to_hex(branch_head
), remote
);
409 /* See if remote matches <name>^^^.. or <name>~<number> */
410 for (len
= 0, ptr
= remote
+ strlen(remote
);
411 remote
< ptr
&& ptr
[-1] == '^';
418 ptr
= strrchr(remote
, '~');
420 int seen_nonzero
= 0;
423 while (*++ptr
&& isdigit(*ptr
)) {
424 seen_nonzero
|= (*ptr
!= '0');
428 len
= 0; /* not ...~<number> */
429 else if (seen_nonzero
)
432 early
= 1; /* "name~" is "name~1"! */
436 struct strbuf truname
= STRBUF_INIT
;
437 strbuf_addstr(&truname
, "refs/heads/");
438 strbuf_addstr(&truname
, remote
);
439 strbuf_setlen(&truname
, truname
.len
- len
);
440 if (resolve_ref(truname
.buf
, buf_sha
, 0, NULL
)) {
442 "%s\t\tbranch '%s'%s of .\n",
443 sha1_to_hex(remote_head
->sha1
),
445 (early
? " (early part)" : ""));
446 strbuf_release(&truname
);
451 if (!strcmp(remote
, "FETCH_HEAD") &&
452 !access(git_path("FETCH_HEAD"), R_OK
)) {
454 struct strbuf line
= STRBUF_INIT
;
457 fp
= fopen(git_path("FETCH_HEAD"), "r");
459 die_errno("could not open '%s' for reading",
460 git_path("FETCH_HEAD"));
461 strbuf_getline(&line
, fp
, '\n');
463 ptr
= strstr(line
.buf
, "\tnot-for-merge\t");
465 strbuf_remove(&line
, ptr
-line
.buf
+1, 13);
466 strbuf_addbuf(msg
, &line
);
467 strbuf_release(&line
);
470 strbuf_addf(msg
, "%s\t\tcommit '%s'\n",
471 sha1_to_hex(remote_head
->sha1
), remote
);
473 strbuf_release(&buf
);
474 strbuf_release(&bname
);
477 static int git_merge_config(const char *k
, const char *v
, void *cb
)
479 if (branch
&& !prefixcmp(k
, "branch.") &&
480 !prefixcmp(k
+ 7, branch
) &&
481 !strcmp(k
+ 7 + strlen(branch
), ".mergeoptions")) {
487 argc
= split_cmdline(buf
, &argv
);
489 die("Bad branch.%s.mergeoptions string", branch
);
490 argv
= xrealloc(argv
, sizeof(*argv
) * (argc
+ 2));
491 memmove(argv
+ 1, argv
, sizeof(*argv
) * (argc
+ 1));
493 parse_options(argc
, argv
, NULL
, builtin_merge_options
,
494 builtin_merge_usage
, 0);
498 if (!strcmp(k
, "merge.diffstat") || !strcmp(k
, "merge.stat"))
499 show_diffstat
= git_config_bool(k
, v
);
500 else if (!strcmp(k
, "pull.twohead"))
501 return git_config_string(&pull_twohead
, k
, v
);
502 else if (!strcmp(k
, "pull.octopus"))
503 return git_config_string(&pull_octopus
, k
, v
);
504 else if (!strcmp(k
, "merge.log") || !strcmp(k
, "merge.summary"))
505 option_log
= git_config_bool(k
, v
);
506 return git_diff_ui_config(k
, v
, cb
);
509 static int read_tree_trivial(unsigned char *common
, unsigned char *head
,
513 struct tree
*trees
[MAX_UNPACK_TREES
];
514 struct tree_desc t
[MAX_UNPACK_TREES
];
515 struct unpack_trees_options opts
;
517 memset(&opts
, 0, sizeof(opts
));
519 opts
.src_index
= &the_index
;
520 opts
.dst_index
= &the_index
;
522 opts
.verbose_update
= 1;
523 opts
.trivial_merges_only
= 1;
525 trees
[nr_trees
] = parse_tree_indirect(common
);
526 if (!trees
[nr_trees
++])
528 trees
[nr_trees
] = parse_tree_indirect(head
);
529 if (!trees
[nr_trees
++])
531 trees
[nr_trees
] = parse_tree_indirect(one
);
532 if (!trees
[nr_trees
++])
534 opts
.fn
= threeway_merge
;
535 cache_tree_free(&active_cache_tree
);
536 for (i
= 0; i
< nr_trees
; i
++) {
537 parse_tree(trees
[i
]);
538 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
540 if (unpack_trees(nr_trees
, t
, &opts
))
545 static void write_tree_trivial(unsigned char *sha1
)
547 if (write_cache_as_tree(sha1
, 0, NULL
))
548 die("git write-tree failed to write a tree");
551 int try_merge_command(const char *strategy
, struct commit_list
*common
,
552 const char *head_arg
, struct commit_list
*remotes
)
555 int i
= 0, x
= 0, ret
;
556 struct commit_list
*j
;
557 struct strbuf buf
= STRBUF_INIT
;
559 args
= xmalloc((4 + xopts_nr
+ commit_list_count(common
) +
560 commit_list_count(remotes
)) * sizeof(char *));
561 strbuf_addf(&buf
, "merge-%s", strategy
);
563 for (x
= 0; x
< xopts_nr
; x
++) {
564 char *s
= xmalloc(strlen(xopts
[x
])+2+1);
566 strcpy(s
+2, xopts
[x
]);
569 for (j
= common
; j
; j
= j
->next
)
570 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
572 args
[i
++] = head_arg
;
573 for (j
= remotes
; j
; j
= j
->next
)
574 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
576 ret
= run_command_v_opt(args
, RUN_GIT_CMD
);
577 strbuf_release(&buf
);
579 for (x
= 0; x
< xopts_nr
; x
++)
580 free((void *)args
[i
++]);
581 for (j
= common
; j
; j
= j
->next
)
582 free((void *)args
[i
++]);
584 for (j
= remotes
; j
; j
= j
->next
)
585 free((void *)args
[i
++]);
588 if (read_cache() < 0)
589 die("failed to read the cache");
590 resolve_undo_clear();
595 static int try_merge_strategy(const char *strategy
, struct commit_list
*common
,
596 const char *head_arg
)
599 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
601 index_fd
= hold_locked_index(lock
, 1);
602 refresh_cache(REFRESH_QUIET
);
603 if (active_cache_changed
&&
604 (write_cache(index_fd
, active_cache
, active_nr
) ||
605 commit_locked_index(lock
)))
606 return error("Unable to write index.");
607 rollback_lock_file(lock
);
609 if (!strcmp(strategy
, "recursive") || !strcmp(strategy
, "subtree")) {
611 struct commit
*result
;
612 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
614 struct commit_list
*reversed
= NULL
;
615 struct merge_options o
;
616 struct commit_list
*j
;
618 if (remoteheads
->next
) {
619 error("Not handling anything other than two heads merge.");
623 init_merge_options(&o
);
624 if (!strcmp(strategy
, "subtree"))
625 o
.subtree_shift
= "";
627 for (x
= 0; x
< xopts_nr
; x
++) {
628 if (!strcmp(xopts
[x
], "ours"))
629 o
.recursive_variant
= MERGE_RECURSIVE_OURS
;
630 else if (!strcmp(xopts
[x
], "theirs"))
631 o
.recursive_variant
= MERGE_RECURSIVE_THEIRS
;
632 else if (!strcmp(xopts
[x
], "subtree"))
633 o
.subtree_shift
= "";
634 else if (!prefixcmp(xopts
[x
], "subtree="))
635 o
.subtree_shift
= xopts
[x
]+8;
637 die("Unknown option for merge-recursive: -X%s", xopts
[x
]);
640 o
.branch1
= head_arg
;
641 o
.branch2
= remoteheads
->item
->util
;
643 for (j
= common
; j
; j
= j
->next
)
644 commit_list_insert(j
->item
, &reversed
);
646 index_fd
= hold_locked_index(lock
, 1);
647 clean
= merge_recursive(&o
, lookup_commit(head
),
648 remoteheads
->item
, reversed
, &result
);
649 if (active_cache_changed
&&
650 (write_cache(index_fd
, active_cache
, active_nr
) ||
651 commit_locked_index(lock
)))
652 die ("unable to write %s", get_index_file());
653 rollback_lock_file(lock
);
654 return clean
? 0 : 1;
656 return try_merge_command(strategy
, common
, head_arg
, remoteheads
);
660 static void count_diff_files(struct diff_queue_struct
*q
,
661 struct diff_options
*opt
, void *data
)
668 static int count_unmerged_entries(void)
672 for (i
= 0; i
< active_nr
; i
++)
673 if (ce_stage(active_cache
[i
]))
679 int checkout_fast_forward(const unsigned char *head
, const unsigned char *remote
)
681 struct tree
*trees
[MAX_UNPACK_TREES
];
682 struct unpack_trees_options opts
;
683 struct tree_desc t
[MAX_UNPACK_TREES
];
684 int i
, fd
, nr_trees
= 0;
685 struct dir_struct dir
;
686 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
688 refresh_cache(REFRESH_QUIET
);
690 fd
= hold_locked_index(lock_file
, 1);
692 memset(&trees
, 0, sizeof(trees
));
693 memset(&opts
, 0, sizeof(opts
));
694 memset(&t
, 0, sizeof(t
));
695 memset(&dir
, 0, sizeof(dir
));
696 dir
.flags
|= DIR_SHOW_IGNORED
;
697 dir
.exclude_per_dir
= ".gitignore";
701 opts
.src_index
= &the_index
;
702 opts
.dst_index
= &the_index
;
704 opts
.verbose_update
= 1;
706 opts
.fn
= twoway_merge
;
707 set_porcelain_error_msgs(opts
.msgs
);
709 trees
[nr_trees
] = parse_tree_indirect(head
);
710 if (!trees
[nr_trees
++])
712 trees
[nr_trees
] = parse_tree_indirect(remote
);
713 if (!trees
[nr_trees
++])
715 for (i
= 0; i
< nr_trees
; i
++) {
716 parse_tree(trees
[i
]);
717 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
719 if (unpack_trees(nr_trees
, t
, &opts
))
721 if (write_cache(fd
, active_cache
, active_nr
) ||
722 commit_locked_index(lock_file
))
723 die("unable to write new index file");
727 static void split_merge_strategies(const char *string
, struct strategy
**list
,
735 buf
= xstrdup(string
);
740 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
741 (*list
)[(*nr
)++].name
= xstrdup(q
);
746 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
747 (*list
)[(*nr
)++].name
= xstrdup(q
);
753 static void add_strategies(const char *string
, unsigned attr
)
755 struct strategy
*list
= NULL
;
756 int list_alloc
= 0, list_nr
= 0, i
;
758 memset(&list
, 0, sizeof(list
));
759 split_merge_strategies(string
, &list
, &list_nr
, &list_alloc
);
761 for (i
= 0; i
< list_nr
; i
++)
762 append_strategy(get_strategy(list
[i
].name
));
765 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
766 if (all_strategy
[i
].attr
& attr
)
767 append_strategy(&all_strategy
[i
]);
771 static int merge_trivial(void)
773 unsigned char result_tree
[20], result_commit
[20];
774 struct commit_list
*parent
= xmalloc(sizeof(*parent
));
776 write_tree_trivial(result_tree
);
777 printf("Wonderful.\n");
778 parent
->item
= lookup_commit(head
);
779 parent
->next
= xmalloc(sizeof(*parent
->next
));
780 parent
->next
->item
= remoteheads
->item
;
781 parent
->next
->next
= NULL
;
782 commit_tree(merge_msg
.buf
, result_tree
, parent
, result_commit
, NULL
);
783 finish(result_commit
, "In-index merge");
788 static int finish_automerge(struct commit_list
*common
,
789 unsigned char *result_tree
,
790 const char *wt_strategy
)
792 struct commit_list
*parents
= NULL
, *j
;
793 struct strbuf buf
= STRBUF_INIT
;
794 unsigned char result_commit
[20];
796 free_commit_list(common
);
797 if (allow_fast_forward
) {
798 parents
= remoteheads
;
799 commit_list_insert(lookup_commit(head
), &parents
);
800 parents
= reduce_heads(parents
);
802 struct commit_list
**pptr
= &parents
;
804 pptr
= &commit_list_insert(lookup_commit(head
),
806 for (j
= remoteheads
; j
; j
= j
->next
)
807 pptr
= &commit_list_insert(j
->item
, pptr
)->next
;
809 free_commit_list(remoteheads
);
810 strbuf_addch(&merge_msg
, '\n');
811 commit_tree(merge_msg
.buf
, result_tree
, parents
, result_commit
, NULL
);
812 strbuf_addf(&buf
, "Merge made by %s.", wt_strategy
);
813 finish(result_commit
, buf
.buf
);
814 strbuf_release(&buf
);
819 static int suggest_conflicts(void)
824 fp
= fopen(git_path("MERGE_MSG"), "a");
826 die_errno("Could not open '%s' for writing",
827 git_path("MERGE_MSG"));
828 fprintf(fp
, "\nConflicts:\n");
829 for (pos
= 0; pos
< active_nr
; pos
++) {
830 struct cache_entry
*ce
= active_cache
[pos
];
833 fprintf(fp
, "\t%s\n", ce
->name
);
834 while (pos
+ 1 < active_nr
&&
836 active_cache
[pos
+ 1]->name
))
841 rerere(allow_rerere_auto
);
842 printf("Automatic merge failed; "
843 "fix conflicts and then commit the result.\n");
847 static struct commit
*is_old_style_invocation(int argc
, const char **argv
)
849 struct commit
*second_token
= NULL
;
851 unsigned char second_sha1
[20];
853 if (get_sha1(argv
[1], second_sha1
))
855 second_token
= lookup_commit_reference_gently(second_sha1
, 0);
857 die("'%s' is not a commit", argv
[1]);
858 if (hashcmp(second_token
->object
.sha1
, head
))
864 static int evaluate_result(void)
869 /* Check how many files differ. */
870 init_revisions(&rev
, "");
871 setup_revisions(0, NULL
, &rev
, NULL
);
872 rev
.diffopt
.output_format
|=
873 DIFF_FORMAT_CALLBACK
;
874 rev
.diffopt
.format_callback
= count_diff_files
;
875 rev
.diffopt
.format_callback_data
= &cnt
;
876 run_diff_files(&rev
, 0);
879 * Check how many unmerged entries are
882 cnt
+= count_unmerged_entries();
887 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
889 unsigned char result_tree
[20];
890 struct strbuf buf
= STRBUF_INIT
;
891 const char *head_arg
;
892 int flag
, head_invalid
= 0, i
;
893 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
894 struct commit_list
*common
= NULL
;
895 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
896 struct commit_list
**remotes
= &remoteheads
;
898 if (read_cache_unmerged()) {
899 die_resolve_conflict("merge");
901 if (file_exists(git_path("MERGE_HEAD"))) {
903 * There is no unmerged entry, don't advise 'git
904 * add/rm <file>', just 'git commit'.
906 if (advice_resolve_conflict
)
907 die("You have not concluded your merge (MERGE_HEAD exists).\n"
908 "Please, commit your changes before you can merge.");
910 die("You have not concluded your merge (MERGE_HEAD exists).");
913 resolve_undo_clear();
915 * Check if we are _not_ on a detached HEAD, i.e. if there is a
918 branch
= resolve_ref("HEAD", head
, 0, &flag
);
919 if (branch
&& !prefixcmp(branch
, "refs/heads/"))
921 if (is_null_sha1(head
))
924 git_config(git_merge_config
, NULL
);
927 if (diff_use_color_default
== -1)
928 diff_use_color_default
= git_use_color_default
;
930 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
931 builtin_merge_usage
, 0);
936 if (!allow_fast_forward
)
937 die("You cannot combine --squash with --no-ff.");
941 if (!allow_fast_forward
&& fast_forward_only
)
942 die("You cannot combine --no-ff with --ff-only.");
945 usage_with_options(builtin_merge_usage
,
946 builtin_merge_options
);
949 * This could be traditional "merge <msg> HEAD <commit>..." and
950 * the way we can tell it is to see if the second token is HEAD,
951 * but some people might have misused the interface and used a
952 * committish that is the same as HEAD there instead.
953 * Traditional format never would have "-m" so it is an
954 * additional safety measure to check for it.
957 if (!have_message
&& is_old_style_invocation(argc
, argv
)) {
958 strbuf_addstr(&merge_msg
, argv
[0]);
962 } else if (head_invalid
) {
963 struct object
*remote_head
;
965 * If the merged head is a valid one there is no reason
966 * to forbid "git merge" into a branch yet to be born.
967 * We do the same for "git pull".
970 die("Can merge only exactly one commit into "
973 die("Squash commit into empty head not supported yet");
974 if (!allow_fast_forward
)
975 die("Non-fast-forward commit does not make sense into "
977 remote_head
= peel_to_type(argv
[0], 0, NULL
, OBJ_COMMIT
);
979 die("%s - not something we can merge", argv
[0]);
980 update_ref("initial pull", "HEAD", remote_head
->sha1
, NULL
, 0,
982 reset_hard(remote_head
->sha1
, 0);
985 struct strbuf merge_names
= STRBUF_INIT
;
987 /* We are invoked directly as the first-class UI. */
991 * All the rest are the commits being merged;
992 * prepare the standard merge summary message to
993 * be appended to the given message. If remote
994 * is invalid we will die later in the common
995 * codepath so we discard the error in this
998 for (i
= 0; i
< argc
; i
++)
999 merge_name(argv
[i
], &merge_names
);
1001 if (have_message
&& option_log
)
1002 fmt_merge_msg_shortlog(&merge_names
, &merge_msg
);
1003 else if (!have_message
)
1004 fmt_merge_msg(option_log
, &merge_names
, &merge_msg
);
1007 if (!(have_message
&& !option_log
) && merge_msg
.len
)
1008 strbuf_setlen(&merge_msg
, merge_msg
.len
-1);
1011 if (head_invalid
|| !argc
)
1012 usage_with_options(builtin_merge_usage
,
1013 builtin_merge_options
);
1015 strbuf_addstr(&buf
, "merge");
1016 for (i
= 0; i
< argc
; i
++)
1017 strbuf_addf(&buf
, " %s", argv
[i
]);
1018 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
1021 for (i
= 0; i
< argc
; i
++) {
1023 struct commit
*commit
;
1025 o
= peel_to_type(argv
[i
], 0, NULL
, OBJ_COMMIT
);
1027 die("%s - not something we can merge", argv
[i
]);
1028 commit
= lookup_commit(o
->sha1
);
1029 commit
->util
= (void *)argv
[i
];
1030 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1032 strbuf_addf(&buf
, "GITHEAD_%s", sha1_to_hex(o
->sha1
));
1033 setenv(buf
.buf
, argv
[i
], 1);
1037 if (!use_strategies
) {
1038 if (!remoteheads
->next
)
1039 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
1041 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
1044 for (i
= 0; i
< use_strategies_nr
; i
++) {
1045 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
1046 allow_fast_forward
= 0;
1047 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
1051 if (!remoteheads
->next
)
1052 common
= get_merge_bases(lookup_commit(head
),
1053 remoteheads
->item
, 1);
1055 struct commit_list
*list
= remoteheads
;
1056 commit_list_insert(lookup_commit(head
), &list
);
1057 common
= get_octopus_merge_bases(list
);
1061 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head
, NULL
, 0,
1065 ; /* No common ancestors found. We need a real merge. */
1066 else if (!remoteheads
->next
&& !common
->next
&&
1067 common
->item
== remoteheads
->item
) {
1069 * If head can reach all the merge then we are up to date.
1070 * but first the most common case of merging one remote.
1072 finish_up_to_date("Already up-to-date.");
1074 } else if (allow_fast_forward
&& !remoteheads
->next
&&
1076 !hashcmp(common
->item
->object
.sha1
, head
)) {
1077 /* Again the most common case of merging one remote. */
1078 struct strbuf msg
= STRBUF_INIT
;
1082 strcpy(hex
, find_unique_abbrev(head
, DEFAULT_ABBREV
));
1085 printf("Updating %s..%s\n",
1087 find_unique_abbrev(remoteheads
->item
->object
.sha1
,
1089 strbuf_addstr(&msg
, "Fast-forward");
1092 " (no commit created; -m option ignored)");
1093 o
= peel_to_type(sha1_to_hex(remoteheads
->item
->object
.sha1
),
1094 0, NULL
, OBJ_COMMIT
);
1098 if (checkout_fast_forward(head
, remoteheads
->item
->object
.sha1
))
1101 finish(o
->sha1
, msg
.buf
);
1104 } else if (!remoteheads
->next
&& common
->next
)
1107 * We are not doing octopus and not fast-forward. Need
1110 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1112 * We are not doing octopus, not fast-forward, and have
1115 refresh_cache(REFRESH_QUIET
);
1116 if (allow_trivial
&& !fast_forward_only
) {
1117 /* See if it is really trivial. */
1118 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1119 printf("Trying really trivial in-index merge...\n");
1120 if (!read_tree_trivial(common
->item
->object
.sha1
,
1121 head
, remoteheads
->item
->object
.sha1
))
1122 return merge_trivial();
1127 * An octopus. If we can reach all the remote we are up
1131 struct commit_list
*j
;
1133 for (j
= remoteheads
; j
; j
= j
->next
) {
1134 struct commit_list
*common_one
;
1137 * Here we *have* to calculate the individual
1138 * merge_bases again, otherwise "git merge HEAD^
1139 * HEAD^^" would be missed.
1141 common_one
= get_merge_bases(lookup_commit(head
),
1143 if (hashcmp(common_one
->item
->object
.sha1
,
1144 j
->item
->object
.sha1
)) {
1150 finish_up_to_date("Already up-to-date. Yeeah!");
1155 if (fast_forward_only
)
1156 die("Not possible to fast-forward, aborting.");
1158 /* We are going to make a new commit. */
1159 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1162 * At this point, we need a real merge. No matter what strategy
1163 * we use, it would operate on the index, possibly affecting the
1164 * working tree, and when resolved cleanly, have the desired
1165 * tree in the index -- this means that the index must be in
1166 * sync with the head commit. The strategies are responsible
1169 if (use_strategies_nr
!= 1) {
1171 * Stash away the local changes so that we can try more
1176 memcpy(stash
, null_sha1
, 20);
1179 for (i
= 0; i
< use_strategies_nr
; i
++) {
1182 printf("Rewinding the tree to pristine...\n");
1185 if (use_strategies_nr
!= 1)
1186 printf("Trying merge strategy %s...\n",
1187 use_strategies
[i
]->name
);
1189 * Remember which strategy left the state in the working
1192 wt_strategy
= use_strategies
[i
]->name
;
1194 ret
= try_merge_strategy(use_strategies
[i
]->name
,
1196 if (!option_commit
&& !ret
) {
1199 * This is necessary here just to avoid writing
1200 * the tree, but later we will *not* exit with
1201 * status code 1 because merge_was_ok is set.
1208 * The backend exits with 1 when conflicts are
1209 * left to be resolved, with 2 when it does not
1210 * handle the given merge at all.
1213 int cnt
= evaluate_result();
1215 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1216 best_strategy
= use_strategies
[i
]->name
;
1226 /* Automerge succeeded. */
1227 write_tree_trivial(result_tree
);
1228 automerge_was_ok
= 1;
1233 * If we have a resulting tree, that means the strategy module
1234 * auto resolved the merge cleanly.
1236 if (automerge_was_ok
)
1237 return finish_automerge(common
, result_tree
, wt_strategy
);
1240 * Pick the result from the best strategy and have the user fix
1243 if (!best_strategy
) {
1245 if (use_strategies_nr
> 1)
1247 "No merge strategy handled the merge.\n");
1249 fprintf(stderr
, "Merge with strategy %s failed.\n",
1250 use_strategies
[0]->name
);
1252 } else if (best_strategy
== wt_strategy
)
1253 ; /* We already have its result in the working tree. */
1255 printf("Rewinding the tree to pristine...\n");
1257 printf("Using the %s to prepare resolving by hand.\n",
1259 try_merge_strategy(best_strategy
, common
, head_arg
);
1266 struct commit_list
*j
;
1268 for (j
= remoteheads
; j
; j
= j
->next
)
1269 strbuf_addf(&buf
, "%s\n",
1270 sha1_to_hex(j
->item
->object
.sha1
));
1271 fd
= open(git_path("MERGE_HEAD"), O_WRONLY
| O_CREAT
, 0666);
1273 die_errno("Could not open '%s' for writing",
1274 git_path("MERGE_HEAD"));
1275 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1276 die_errno("Could not write to '%s'", git_path("MERGE_HEAD"));
1278 strbuf_addch(&merge_msg
, '\n');
1279 fd
= open(git_path("MERGE_MSG"), O_WRONLY
| O_CREAT
, 0666);
1281 die_errno("Could not open '%s' for writing",
1282 git_path("MERGE_MSG"));
1283 if (write_in_full(fd
, merge_msg
.buf
, merge_msg
.len
) !=
1285 die_errno("Could not write to '%s'", git_path("MERGE_MSG"));
1287 fd
= open(git_path("MERGE_MODE"), O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
1289 die_errno("Could not open '%s' for writing",
1290 git_path("MERGE_MODE"));
1292 if (!allow_fast_forward
)
1293 strbuf_addf(&buf
, "no-ff");
1294 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1295 die_errno("Could not write to '%s'", git_path("MERGE_MODE"));
1300 fprintf(stderr
, "Automatic merge went well; "
1301 "stopped before committing as requested\n");
1304 return suggest_conflicts();