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 *branch
;
57 static struct strategy all_strategy
[] = {
58 { "recursive", DEFAULT_TWOHEAD
| NO_TRIVIAL
},
59 { "octopus", DEFAULT_OCTOPUS
},
61 { "ours", NO_FAST_FORWARD
| NO_TRIVIAL
},
62 { "subtree", NO_FAST_FORWARD
| NO_TRIVIAL
},
65 static const char *pull_twohead
, *pull_octopus
;
67 static int option_parse_message(const struct option
*opt
,
68 const char *arg
, int unset
)
70 struct strbuf
*buf
= opt
->value
;
73 strbuf_setlen(buf
, 0);
75 strbuf_addf(buf
, "%s%s", buf
->len
? "\n\n" : "", arg
);
78 return error("switch `m' requires a value");
82 static struct strategy
*get_strategy(const char *name
)
86 static struct cmdnames main_cmds
, other_cmds
;
92 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
93 if (!strcmp(name
, all_strategy
[i
].name
))
94 return &all_strategy
[i
];
97 struct cmdnames not_strategies
;
100 memset(¬_strategies
, 0, sizeof(struct cmdnames
));
101 load_command_list("git-merge-", &main_cmds
, &other_cmds
);
102 for (i
= 0; i
< main_cmds
.cnt
; i
++) {
104 struct cmdname
*ent
= main_cmds
.names
[i
];
105 for (j
= 0; j
< ARRAY_SIZE(all_strategy
); j
++)
106 if (!strncmp(ent
->name
, all_strategy
[j
].name
, ent
->len
)
107 && !all_strategy
[j
].name
[ent
->len
])
110 add_cmdname(¬_strategies
, ent
->name
, ent
->len
);
112 exclude_cmds(&main_cmds
, ¬_strategies
);
114 if (!is_in_cmdlist(&main_cmds
, name
) && !is_in_cmdlist(&other_cmds
, name
)) {
115 fprintf(stderr
, "Could not find merge strategy '%s'.\n", name
);
116 fprintf(stderr
, "Available strategies are:");
117 for (i
= 0; i
< main_cmds
.cnt
; i
++)
118 fprintf(stderr
, " %s", main_cmds
.names
[i
]->name
);
119 fprintf(stderr
, ".\n");
120 if (other_cmds
.cnt
) {
121 fprintf(stderr
, "Available custom strategies are:");
122 for (i
= 0; i
< other_cmds
.cnt
; i
++)
123 fprintf(stderr
, " %s", other_cmds
.names
[i
]->name
);
124 fprintf(stderr
, ".\n");
129 ret
= xcalloc(1, sizeof(struct strategy
));
130 ret
->name
= xstrdup(name
);
134 static void append_strategy(struct strategy
*s
)
136 ALLOC_GROW(use_strategies
, use_strategies_nr
+ 1, use_strategies_alloc
);
137 use_strategies
[use_strategies_nr
++] = s
;
140 static int option_parse_strategy(const struct option
*opt
,
141 const char *name
, int unset
)
146 append_strategy(get_strategy(name
));
150 static int option_parse_n(const struct option
*opt
,
151 const char *arg
, int unset
)
153 show_diffstat
= unset
;
157 static struct option builtin_merge_options
[] = {
158 { OPTION_CALLBACK
, 'n', NULL
, NULL
, NULL
,
159 "do not show a diffstat at the end of the merge",
160 PARSE_OPT_NOARG
, option_parse_n
},
161 OPT_BOOLEAN(0, "stat", &show_diffstat
,
162 "show a diffstat at the end of the merge"),
163 OPT_BOOLEAN(0, "summary", &show_diffstat
, "(synonym to --stat)"),
164 OPT_BOOLEAN(0, "log", &option_log
,
165 "add list of one-line log to merge commit message"),
166 OPT_BOOLEAN(0, "squash", &squash
,
167 "create a single commit instead of doing a merge"),
168 OPT_BOOLEAN(0, "commit", &option_commit
,
169 "perform a commit if the merge succeeds (default)"),
170 OPT_BOOLEAN(0, "ff", &allow_fast_forward
,
171 "allow fast-forward (default)"),
172 OPT_BOOLEAN(0, "ff-only", &fast_forward_only
,
173 "abort if fast-forward is not possible"),
174 OPT_CALLBACK('s', "strategy", &use_strategies
, "strategy",
175 "merge strategy to use", option_parse_strategy
),
176 OPT_CALLBACK('m', "message", &merge_msg
, "message",
177 "message to be used for the merge commit (if any)",
178 option_parse_message
),
179 OPT__VERBOSITY(&verbosity
),
183 /* Cleans up metadata that is uninteresting after a succeeded merge. */
184 static void drop_save(void)
186 unlink(git_path("MERGE_HEAD"));
187 unlink(git_path("MERGE_MSG"));
188 unlink(git_path("MERGE_MODE"));
191 static void save_state(void)
194 struct child_process cp
;
195 struct strbuf buffer
= STRBUF_INIT
;
196 const char *argv
[] = {"stash", "create", NULL
};
198 memset(&cp
, 0, sizeof(cp
));
203 if (start_command(&cp
))
204 die("could not run stash.");
205 len
= strbuf_read(&buffer
, cp
.out
, 1024);
208 if (finish_command(&cp
) || len
< 0)
212 strbuf_setlen(&buffer
, buffer
.len
-1);
213 if (get_sha1(buffer
.buf
, stash
))
214 die("not a valid object: %s", buffer
.buf
);
217 static void reset_hard(unsigned const char *sha1
, int verbose
)
222 args
[i
++] = "read-tree";
225 args
[i
++] = "--reset";
227 args
[i
++] = sha1_to_hex(sha1
);
230 if (run_command_v_opt(args
, RUN_GIT_CMD
))
231 die("read-tree failed");
234 static void restore_state(void)
236 struct strbuf sb
= STRBUF_INIT
;
237 const char *args
[] = { "stash", "apply", NULL
, NULL
};
239 if (is_null_sha1(stash
))
244 args
[2] = sha1_to_hex(stash
);
247 * It is OK to ignore error here, for example when there was
248 * nothing to restore.
250 run_command_v_opt(args
, RUN_GIT_CMD
);
253 refresh_cache(REFRESH_QUIET
);
256 /* This is called when no merge was necessary. */
257 static void finish_up_to_date(const char *msg
)
260 printf("%s%s\n", squash
? " (nothing to squash)" : "", msg
);
264 static void squash_message(void)
267 struct commit
*commit
;
268 struct strbuf out
= STRBUF_INIT
;
269 struct commit_list
*j
;
271 struct pretty_print_context ctx
= {0};
273 printf("Squash commit -- not updating HEAD\n");
274 fd
= open(git_path("SQUASH_MSG"), O_WRONLY
| O_CREAT
, 0666);
276 die_errno("Could not write to '%s'", git_path("SQUASH_MSG"));
278 init_revisions(&rev
, NULL
);
279 rev
.ignore_merges
= 1;
280 rev
.commit_format
= CMIT_FMT_MEDIUM
;
282 commit
= lookup_commit(head
);
283 commit
->object
.flags
|= UNINTERESTING
;
284 add_pending_object(&rev
, &commit
->object
, NULL
);
286 for (j
= remoteheads
; j
; j
= j
->next
)
287 add_pending_object(&rev
, &j
->item
->object
, NULL
);
289 setup_revisions(0, NULL
, &rev
, NULL
);
290 if (prepare_revision_walk(&rev
))
291 die("revision walk setup failed");
293 ctx
.abbrev
= rev
.abbrev
;
294 ctx
.date_mode
= rev
.date_mode
;
296 strbuf_addstr(&out
, "Squashed commit of the following:\n");
297 while ((commit
= get_revision(&rev
)) != NULL
) {
298 strbuf_addch(&out
, '\n');
299 strbuf_addf(&out
, "commit %s\n",
300 sha1_to_hex(commit
->object
.sha1
));
301 pretty_print_commit(rev
.commit_format
, commit
, &out
, &ctx
);
303 if (write(fd
, out
.buf
, out
.len
) < 0)
304 die_errno("Writing SQUASH_MSG");
306 die_errno("Finishing SQUASH_MSG");
307 strbuf_release(&out
);
310 static void finish(const unsigned char *new_head
, const char *msg
)
312 struct strbuf reflog_message
= STRBUF_INIT
;
315 strbuf_addstr(&reflog_message
, getenv("GIT_REFLOG_ACTION"));
319 strbuf_addf(&reflog_message
, "%s: %s",
320 getenv("GIT_REFLOG_ACTION"), msg
);
325 if (verbosity
>= 0 && !merge_msg
.len
)
326 printf("No merge message -- not updating HEAD\n");
328 const char *argv_gc_auto
[] = { "gc", "--auto", NULL
};
329 update_ref(reflog_message
.buf
, "HEAD",
333 * We ignore errors in 'gc --auto', since the
334 * user should see them.
336 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
339 if (new_head
&& show_diffstat
) {
340 struct diff_options opts
;
342 opts
.output_format
|=
343 DIFF_FORMAT_SUMMARY
| DIFF_FORMAT_DIFFSTAT
;
344 opts
.detect_rename
= DIFF_DETECT_RENAME
;
345 if (diff_use_color_default
> 0)
346 DIFF_OPT_SET(&opts
, COLOR_DIFF
);
347 if (diff_setup_done(&opts
) < 0)
348 die("diff_setup_done failed");
349 diff_tree_sha1(head
, new_head
, "", &opts
);
354 /* Run a post-merge hook */
355 run_hook(NULL
, "post-merge", squash
? "1" : "0", NULL
);
357 strbuf_release(&reflog_message
);
360 /* Get the name for the merge commit's message. */
361 static void merge_name(const char *remote
, struct strbuf
*msg
)
363 struct object
*remote_head
;
364 unsigned char branch_head
[20], buf_sha
[20];
365 struct strbuf buf
= STRBUF_INIT
;
366 struct strbuf bname
= STRBUF_INIT
;
371 strbuf_branchname(&bname
, remote
);
374 memset(branch_head
, 0, sizeof(branch_head
));
375 remote_head
= peel_to_type(remote
, 0, NULL
, OBJ_COMMIT
);
377 die("'%s' does not point to a commit", remote
);
379 if (dwim_ref(remote
, strlen(remote
), branch_head
, &found_ref
) > 0) {
380 if (!prefixcmp(found_ref
, "refs/heads/")) {
381 strbuf_addf(msg
, "%s\t\tbranch '%s' of .\n",
382 sha1_to_hex(branch_head
), remote
);
385 if (!prefixcmp(found_ref
, "refs/remotes/")) {
386 strbuf_addf(msg
, "%s\t\tremote branch '%s' of .\n",
387 sha1_to_hex(branch_head
), remote
);
392 /* See if remote matches <name>^^^.. or <name>~<number> */
393 for (len
= 0, ptr
= remote
+ strlen(remote
);
394 remote
< ptr
&& ptr
[-1] == '^';
401 ptr
= strrchr(remote
, '~');
403 int seen_nonzero
= 0;
406 while (*++ptr
&& isdigit(*ptr
)) {
407 seen_nonzero
|= (*ptr
!= '0');
411 len
= 0; /* not ...~<number> */
412 else if (seen_nonzero
)
415 early
= 1; /* "name~" is "name~1"! */
419 struct strbuf truname
= STRBUF_INIT
;
420 strbuf_addstr(&truname
, "refs/heads/");
421 strbuf_addstr(&truname
, remote
);
422 strbuf_setlen(&truname
, truname
.len
- len
);
423 if (resolve_ref(truname
.buf
, buf_sha
, 0, NULL
)) {
425 "%s\t\tbranch '%s'%s of .\n",
426 sha1_to_hex(remote_head
->sha1
),
428 (early
? " (early part)" : ""));
429 strbuf_release(&truname
);
434 if (!strcmp(remote
, "FETCH_HEAD") &&
435 !access(git_path("FETCH_HEAD"), R_OK
)) {
437 struct strbuf line
= STRBUF_INIT
;
440 fp
= fopen(git_path("FETCH_HEAD"), "r");
442 die_errno("could not open '%s' for reading",
443 git_path("FETCH_HEAD"));
444 strbuf_getline(&line
, fp
, '\n');
446 ptr
= strstr(line
.buf
, "\tnot-for-merge\t");
448 strbuf_remove(&line
, ptr
-line
.buf
+1, 13);
449 strbuf_addbuf(msg
, &line
);
450 strbuf_release(&line
);
453 strbuf_addf(msg
, "%s\t\tcommit '%s'\n",
454 sha1_to_hex(remote_head
->sha1
), remote
);
456 strbuf_release(&buf
);
457 strbuf_release(&bname
);
460 static int git_merge_config(const char *k
, const char *v
, void *cb
)
462 if (branch
&& !prefixcmp(k
, "branch.") &&
463 !prefixcmp(k
+ 7, branch
) &&
464 !strcmp(k
+ 7 + strlen(branch
), ".mergeoptions")) {
470 argc
= split_cmdline(buf
, &argv
);
472 die("Bad branch.%s.mergeoptions string", branch
);
473 argv
= xrealloc(argv
, sizeof(*argv
) * (argc
+ 2));
474 memmove(argv
+ 1, argv
, sizeof(*argv
) * (argc
+ 1));
476 parse_options(argc
, argv
, NULL
, builtin_merge_options
,
477 builtin_merge_usage
, 0);
481 if (!strcmp(k
, "merge.diffstat") || !strcmp(k
, "merge.stat"))
482 show_diffstat
= git_config_bool(k
, v
);
483 else if (!strcmp(k
, "pull.twohead"))
484 return git_config_string(&pull_twohead
, k
, v
);
485 else if (!strcmp(k
, "pull.octopus"))
486 return git_config_string(&pull_octopus
, k
, v
);
487 else if (!strcmp(k
, "merge.log") || !strcmp(k
, "merge.summary"))
488 option_log
= git_config_bool(k
, v
);
489 return git_diff_ui_config(k
, v
, cb
);
492 static int read_tree_trivial(unsigned char *common
, unsigned char *head
,
496 struct tree
*trees
[MAX_UNPACK_TREES
];
497 struct tree_desc t
[MAX_UNPACK_TREES
];
498 struct unpack_trees_options opts
;
500 memset(&opts
, 0, sizeof(opts
));
502 opts
.src_index
= &the_index
;
503 opts
.dst_index
= &the_index
;
505 opts
.verbose_update
= 1;
506 opts
.trivial_merges_only
= 1;
508 trees
[nr_trees
] = parse_tree_indirect(common
);
509 if (!trees
[nr_trees
++])
511 trees
[nr_trees
] = parse_tree_indirect(head
);
512 if (!trees
[nr_trees
++])
514 trees
[nr_trees
] = parse_tree_indirect(one
);
515 if (!trees
[nr_trees
++])
517 opts
.fn
= threeway_merge
;
518 cache_tree_free(&active_cache_tree
);
519 for (i
= 0; i
< nr_trees
; i
++) {
520 parse_tree(trees
[i
]);
521 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
523 if (unpack_trees(nr_trees
, t
, &opts
))
528 static void write_tree_trivial(unsigned char *sha1
)
530 if (write_cache_as_tree(sha1
, 0, NULL
))
531 die("git write-tree failed to write a tree");
534 static int try_merge_strategy(const char *strategy
, struct commit_list
*common
,
535 const char *head_arg
)
539 struct commit_list
*j
;
540 struct strbuf buf
= STRBUF_INIT
;
542 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
544 index_fd
= hold_locked_index(lock
, 1);
545 refresh_cache(REFRESH_QUIET
);
546 if (active_cache_changed
&&
547 (write_cache(index_fd
, active_cache
, active_nr
) ||
548 commit_locked_index(lock
)))
549 return error("Unable to write index.");
550 rollback_lock_file(lock
);
552 if (!strcmp(strategy
, "recursive") || !strcmp(strategy
, "subtree")) {
554 struct commit
*result
;
555 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
557 struct commit_list
*reversed
= NULL
;
558 struct merge_options o
;
560 if (remoteheads
->next
) {
561 error("Not handling anything other than two heads merge.");
565 init_merge_options(&o
);
566 if (!strcmp(strategy
, "subtree"))
569 o
.branch1
= head_arg
;
570 o
.branch2
= remoteheads
->item
->util
;
572 for (j
= common
; j
; j
= j
->next
)
573 commit_list_insert(j
->item
, &reversed
);
575 index_fd
= hold_locked_index(lock
, 1);
576 clean
= merge_recursive(&o
, lookup_commit(head
),
577 remoteheads
->item
, reversed
, &result
);
578 if (active_cache_changed
&&
579 (write_cache(index_fd
, active_cache
, active_nr
) ||
580 commit_locked_index(lock
)))
581 die ("unable to write %s", get_index_file());
582 rollback_lock_file(lock
);
583 return clean
? 0 : 1;
585 args
= xmalloc((4 + commit_list_count(common
) +
586 commit_list_count(remoteheads
)) * sizeof(char *));
587 strbuf_addf(&buf
, "merge-%s", strategy
);
589 for (j
= common
; j
; j
= j
->next
)
590 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
592 args
[i
++] = head_arg
;
593 for (j
= remoteheads
; j
; j
= j
->next
)
594 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
596 ret
= run_command_v_opt(args
, RUN_GIT_CMD
);
597 strbuf_release(&buf
);
599 for (j
= common
; j
; j
= j
->next
)
600 free((void *)args
[i
++]);
602 for (j
= remoteheads
; j
; j
= j
->next
)
603 free((void *)args
[i
++]);
606 if (read_cache() < 0)
607 die("failed to read the cache");
608 resolve_undo_clear();
613 static void count_diff_files(struct diff_queue_struct
*q
,
614 struct diff_options
*opt
, void *data
)
621 static int count_unmerged_entries(void)
625 for (i
= 0; i
< active_nr
; i
++)
626 if (ce_stage(active_cache
[i
]))
632 static int checkout_fast_forward(unsigned char *head
, unsigned char *remote
)
634 struct tree
*trees
[MAX_UNPACK_TREES
];
635 struct unpack_trees_options opts
;
636 struct tree_desc t
[MAX_UNPACK_TREES
];
637 int i
, fd
, nr_trees
= 0;
638 struct dir_struct dir
;
639 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
641 refresh_cache(REFRESH_QUIET
);
643 fd
= hold_locked_index(lock_file
, 1);
645 memset(&trees
, 0, sizeof(trees
));
646 memset(&opts
, 0, sizeof(opts
));
647 memset(&t
, 0, sizeof(t
));
648 memset(&dir
, 0, sizeof(dir
));
649 dir
.flags
|= DIR_SHOW_IGNORED
;
650 dir
.exclude_per_dir
= ".gitignore";
654 opts
.src_index
= &the_index
;
655 opts
.dst_index
= &the_index
;
657 opts
.verbose_update
= 1;
659 opts
.fn
= twoway_merge
;
660 opts
.msgs
= get_porcelain_error_msgs();
662 trees
[nr_trees
] = parse_tree_indirect(head
);
663 if (!trees
[nr_trees
++])
665 trees
[nr_trees
] = parse_tree_indirect(remote
);
666 if (!trees
[nr_trees
++])
668 for (i
= 0; i
< nr_trees
; i
++) {
669 parse_tree(trees
[i
]);
670 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
672 if (unpack_trees(nr_trees
, t
, &opts
))
674 if (write_cache(fd
, active_cache
, active_nr
) ||
675 commit_locked_index(lock_file
))
676 die("unable to write new index file");
680 static void split_merge_strategies(const char *string
, struct strategy
**list
,
688 buf
= xstrdup(string
);
693 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
694 (*list
)[(*nr
)++].name
= xstrdup(q
);
699 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
700 (*list
)[(*nr
)++].name
= xstrdup(q
);
706 static void add_strategies(const char *string
, unsigned attr
)
708 struct strategy
*list
= NULL
;
709 int list_alloc
= 0, list_nr
= 0, i
;
711 memset(&list
, 0, sizeof(list
));
712 split_merge_strategies(string
, &list
, &list_nr
, &list_alloc
);
714 for (i
= 0; i
< list_nr
; i
++)
715 append_strategy(get_strategy(list
[i
].name
));
718 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
719 if (all_strategy
[i
].attr
& attr
)
720 append_strategy(&all_strategy
[i
]);
724 static int merge_trivial(void)
726 unsigned char result_tree
[20], result_commit
[20];
727 struct commit_list
*parent
= xmalloc(sizeof(*parent
));
729 write_tree_trivial(result_tree
);
730 printf("Wonderful.\n");
731 parent
->item
= lookup_commit(head
);
732 parent
->next
= xmalloc(sizeof(*parent
->next
));
733 parent
->next
->item
= remoteheads
->item
;
734 parent
->next
->next
= NULL
;
735 commit_tree(merge_msg
.buf
, result_tree
, parent
, result_commit
, NULL
);
736 finish(result_commit
, "In-index merge");
741 static int finish_automerge(struct commit_list
*common
,
742 unsigned char *result_tree
,
743 const char *wt_strategy
)
745 struct commit_list
*parents
= NULL
, *j
;
746 struct strbuf buf
= STRBUF_INIT
;
747 unsigned char result_commit
[20];
749 free_commit_list(common
);
750 if (allow_fast_forward
) {
751 parents
= remoteheads
;
752 commit_list_insert(lookup_commit(head
), &parents
);
753 parents
= reduce_heads(parents
);
755 struct commit_list
**pptr
= &parents
;
757 pptr
= &commit_list_insert(lookup_commit(head
),
759 for (j
= remoteheads
; j
; j
= j
->next
)
760 pptr
= &commit_list_insert(j
->item
, pptr
)->next
;
762 free_commit_list(remoteheads
);
763 strbuf_addch(&merge_msg
, '\n');
764 commit_tree(merge_msg
.buf
, result_tree
, parents
, result_commit
, NULL
);
765 strbuf_addf(&buf
, "Merge made by %s.", wt_strategy
);
766 finish(result_commit
, buf
.buf
);
767 strbuf_release(&buf
);
772 static int suggest_conflicts(void)
777 fp
= fopen(git_path("MERGE_MSG"), "a");
779 die_errno("Could not open '%s' for writing",
780 git_path("MERGE_MSG"));
781 fprintf(fp
, "\nConflicts:\n");
782 for (pos
= 0; pos
< active_nr
; pos
++) {
783 struct cache_entry
*ce
= active_cache
[pos
];
786 fprintf(fp
, "\t%s\n", ce
->name
);
787 while (pos
+ 1 < active_nr
&&
789 active_cache
[pos
+ 1]->name
))
795 printf("Automatic merge failed; "
796 "fix conflicts and then commit the result.\n");
800 static struct commit
*is_old_style_invocation(int argc
, const char **argv
)
802 struct commit
*second_token
= NULL
;
804 unsigned char second_sha1
[20];
806 if (get_sha1(argv
[1], second_sha1
))
808 second_token
= lookup_commit_reference_gently(second_sha1
, 0);
810 die("'%s' is not a commit", argv
[1]);
811 if (hashcmp(second_token
->object
.sha1
, head
))
817 static int evaluate_result(void)
822 /* Check how many files differ. */
823 init_revisions(&rev
, "");
824 setup_revisions(0, NULL
, &rev
, NULL
);
825 rev
.diffopt
.output_format
|=
826 DIFF_FORMAT_CALLBACK
;
827 rev
.diffopt
.format_callback
= count_diff_files
;
828 rev
.diffopt
.format_callback_data
= &cnt
;
829 run_diff_files(&rev
, 0);
832 * Check how many unmerged entries are
835 cnt
+= count_unmerged_entries();
840 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
842 unsigned char result_tree
[20];
843 struct strbuf buf
= STRBUF_INIT
;
844 const char *head_arg
;
845 int flag
, head_invalid
= 0, i
;
846 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
847 struct commit_list
*common
= NULL
;
848 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
849 struct commit_list
**remotes
= &remoteheads
;
851 if (file_exists(git_path("MERGE_HEAD")))
852 die("You have not concluded your merge. (MERGE_HEAD exists)");
853 if (read_cache_unmerged())
854 die("You are in the middle of a conflicted merge."
855 " (index unmerged)");
856 resolve_undo_clear();
858 * Check if we are _not_ on a detached HEAD, i.e. if there is a
861 branch
= resolve_ref("HEAD", head
, 0, &flag
);
862 if (branch
&& !prefixcmp(branch
, "refs/heads/"))
864 if (is_null_sha1(head
))
867 git_config(git_merge_config
, NULL
);
870 if (diff_use_color_default
== -1)
871 diff_use_color_default
= git_use_color_default
;
873 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
874 builtin_merge_usage
, 0);
879 if (!allow_fast_forward
)
880 die("You cannot combine --squash with --no-ff.");
884 if (!allow_fast_forward
&& fast_forward_only
)
885 die("You cannot combine --no-ff with --ff-only.");
888 usage_with_options(builtin_merge_usage
,
889 builtin_merge_options
);
892 * This could be traditional "merge <msg> HEAD <commit>..." and
893 * the way we can tell it is to see if the second token is HEAD,
894 * but some people might have misused the interface and used a
895 * committish that is the same as HEAD there instead.
896 * Traditional format never would have "-m" so it is an
897 * additional safety measure to check for it.
900 if (!have_message
&& is_old_style_invocation(argc
, argv
)) {
901 strbuf_addstr(&merge_msg
, argv
[0]);
905 } else if (head_invalid
) {
906 struct object
*remote_head
;
908 * If the merged head is a valid one there is no reason
909 * to forbid "git merge" into a branch yet to be born.
910 * We do the same for "git pull".
913 die("Can merge only exactly one commit into "
916 die("Squash commit into empty head not supported yet");
917 if (!allow_fast_forward
)
918 die("Non-fast-forward commit does not make sense into "
920 remote_head
= peel_to_type(argv
[0], 0, NULL
, OBJ_COMMIT
);
922 die("%s - not something we can merge", argv
[0]);
923 update_ref("initial pull", "HEAD", remote_head
->sha1
, NULL
, 0,
925 reset_hard(remote_head
->sha1
, 0);
928 struct strbuf msg
= STRBUF_INIT
;
930 /* We are invoked directly as the first-class UI. */
934 * All the rest are the commits being merged;
935 * prepare the standard merge summary message to
936 * be appended to the given message. If remote
937 * is invalid we will die later in the common
938 * codepath so we discard the error in this
942 for (i
= 0; i
< argc
; i
++)
943 merge_name(argv
[i
], &msg
);
944 fmt_merge_msg(option_log
, &msg
, &merge_msg
);
946 strbuf_setlen(&merge_msg
, merge_msg
.len
-1);
950 if (head_invalid
|| !argc
)
951 usage_with_options(builtin_merge_usage
,
952 builtin_merge_options
);
954 strbuf_addstr(&buf
, "merge");
955 for (i
= 0; i
< argc
; i
++)
956 strbuf_addf(&buf
, " %s", argv
[i
]);
957 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
960 for (i
= 0; i
< argc
; i
++) {
962 struct commit
*commit
;
964 o
= peel_to_type(argv
[i
], 0, NULL
, OBJ_COMMIT
);
966 die("%s - not something we can merge", argv
[i
]);
967 commit
= lookup_commit(o
->sha1
);
968 commit
->util
= (void *)argv
[i
];
969 remotes
= &commit_list_insert(commit
, remotes
)->next
;
971 strbuf_addf(&buf
, "GITHEAD_%s", sha1_to_hex(o
->sha1
));
972 setenv(buf
.buf
, argv
[i
], 1);
976 if (!use_strategies
) {
977 if (!remoteheads
->next
)
978 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
980 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
983 for (i
= 0; i
< use_strategies_nr
; i
++) {
984 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
985 allow_fast_forward
= 0;
986 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
990 if (!remoteheads
->next
)
991 common
= get_merge_bases(lookup_commit(head
),
992 remoteheads
->item
, 1);
994 struct commit_list
*list
= remoteheads
;
995 commit_list_insert(lookup_commit(head
), &list
);
996 common
= get_octopus_merge_bases(list
);
1000 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head
, NULL
, 0,
1004 ; /* No common ancestors found. We need a real merge. */
1005 else if (!remoteheads
->next
&& !common
->next
&&
1006 common
->item
== remoteheads
->item
) {
1008 * If head can reach all the merge then we are up to date.
1009 * but first the most common case of merging one remote.
1011 finish_up_to_date("Already up-to-date.");
1013 } else if (allow_fast_forward
&& !remoteheads
->next
&&
1015 !hashcmp(common
->item
->object
.sha1
, head
)) {
1016 /* Again the most common case of merging one remote. */
1017 struct strbuf msg
= STRBUF_INIT
;
1021 strcpy(hex
, find_unique_abbrev(head
, DEFAULT_ABBREV
));
1024 printf("Updating %s..%s\n",
1026 find_unique_abbrev(remoteheads
->item
->object
.sha1
,
1028 strbuf_addstr(&msg
, "Fast-forward");
1031 " (no commit created; -m option ignored)");
1032 o
= peel_to_type(sha1_to_hex(remoteheads
->item
->object
.sha1
),
1033 0, NULL
, OBJ_COMMIT
);
1037 if (checkout_fast_forward(head
, remoteheads
->item
->object
.sha1
))
1040 finish(o
->sha1
, msg
.buf
);
1043 } else if (!remoteheads
->next
&& common
->next
)
1046 * We are not doing octopus and not fast-forward. Need
1049 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1051 * We are not doing octopus, not fast-forward, and have
1054 refresh_cache(REFRESH_QUIET
);
1055 if (allow_trivial
&& !fast_forward_only
) {
1056 /* See if it is really trivial. */
1057 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1058 printf("Trying really trivial in-index merge...\n");
1059 if (!read_tree_trivial(common
->item
->object
.sha1
,
1060 head
, remoteheads
->item
->object
.sha1
))
1061 return merge_trivial();
1066 * An octopus. If we can reach all the remote we are up
1070 struct commit_list
*j
;
1072 for (j
= remoteheads
; j
; j
= j
->next
) {
1073 struct commit_list
*common_one
;
1076 * Here we *have* to calculate the individual
1077 * merge_bases again, otherwise "git merge HEAD^
1078 * HEAD^^" would be missed.
1080 common_one
= get_merge_bases(lookup_commit(head
),
1082 if (hashcmp(common_one
->item
->object
.sha1
,
1083 j
->item
->object
.sha1
)) {
1089 finish_up_to_date("Already up-to-date. Yeeah!");
1094 if (fast_forward_only
)
1095 die("Not possible to fast-forward, aborting.");
1097 /* We are going to make a new commit. */
1098 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1101 * At this point, we need a real merge. No matter what strategy
1102 * we use, it would operate on the index, possibly affecting the
1103 * working tree, and when resolved cleanly, have the desired
1104 * tree in the index -- this means that the index must be in
1105 * sync with the head commit. The strategies are responsible
1108 if (use_strategies_nr
!= 1) {
1110 * Stash away the local changes so that we can try more
1115 memcpy(stash
, null_sha1
, 20);
1118 for (i
= 0; i
< use_strategies_nr
; i
++) {
1121 printf("Rewinding the tree to pristine...\n");
1124 if (use_strategies_nr
!= 1)
1125 printf("Trying merge strategy %s...\n",
1126 use_strategies
[i
]->name
);
1128 * Remember which strategy left the state in the working
1131 wt_strategy
= use_strategies
[i
]->name
;
1133 ret
= try_merge_strategy(use_strategies
[i
]->name
,
1135 if (!option_commit
&& !ret
) {
1138 * This is necessary here just to avoid writing
1139 * the tree, but later we will *not* exit with
1140 * status code 1 because merge_was_ok is set.
1147 * The backend exits with 1 when conflicts are
1148 * left to be resolved, with 2 when it does not
1149 * handle the given merge at all.
1152 int cnt
= evaluate_result();
1154 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1155 best_strategy
= use_strategies
[i
]->name
;
1165 /* Automerge succeeded. */
1166 write_tree_trivial(result_tree
);
1167 automerge_was_ok
= 1;
1172 * If we have a resulting tree, that means the strategy module
1173 * auto resolved the merge cleanly.
1175 if (automerge_was_ok
)
1176 return finish_automerge(common
, result_tree
, wt_strategy
);
1179 * Pick the result from the best strategy and have the user fix
1182 if (!best_strategy
) {
1184 if (use_strategies_nr
> 1)
1186 "No merge strategy handled the merge.\n");
1188 fprintf(stderr
, "Merge with strategy %s failed.\n",
1189 use_strategies
[0]->name
);
1191 } else if (best_strategy
== wt_strategy
)
1192 ; /* We already have its result in the working tree. */
1194 printf("Rewinding the tree to pristine...\n");
1196 printf("Using the %s to prepare resolving by hand.\n",
1198 try_merge_strategy(best_strategy
, common
, head_arg
);
1205 struct commit_list
*j
;
1207 for (j
= remoteheads
; j
; j
= j
->next
)
1208 strbuf_addf(&buf
, "%s\n",
1209 sha1_to_hex(j
->item
->object
.sha1
));
1210 fd
= open(git_path("MERGE_HEAD"), O_WRONLY
| O_CREAT
, 0666);
1212 die_errno("Could not open '%s' for writing",
1213 git_path("MERGE_HEAD"));
1214 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1215 die_errno("Could not write to '%s'", git_path("MERGE_HEAD"));
1217 strbuf_addch(&merge_msg
, '\n');
1218 fd
= open(git_path("MERGE_MSG"), O_WRONLY
| O_CREAT
, 0666);
1220 die_errno("Could not open '%s' for writing",
1221 git_path("MERGE_MSG"));
1222 if (write_in_full(fd
, merge_msg
.buf
, merge_msg
.len
) !=
1224 die_errno("Could not write to '%s'", git_path("MERGE_MSG"));
1226 fd
= open(git_path("MERGE_MODE"), O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
1228 die_errno("Could not open '%s' for writing",
1229 git_path("MERGE_MODE"));
1231 if (!allow_fast_forward
)
1232 strbuf_addf(&buf
, "no-ff");
1233 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1234 die_errno("Could not write to '%s'", git_path("MERGE_MODE"));
1239 fprintf(stderr
, "Automatic merge went well; "
1240 "stopped before committing as requested\n");
1243 return suggest_conflicts();