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
;
56 static int allow_rerere_auto
;
58 static struct strategy all_strategy
[] = {
59 { "recursive", DEFAULT_TWOHEAD
| NO_TRIVIAL
},
60 { "octopus", DEFAULT_OCTOPUS
},
62 { "ours", NO_FAST_FORWARD
| NO_TRIVIAL
},
63 { "subtree", NO_FAST_FORWARD
| NO_TRIVIAL
},
66 static const char *pull_twohead
, *pull_octopus
;
68 static int option_parse_message(const struct option
*opt
,
69 const char *arg
, int unset
)
71 struct strbuf
*buf
= opt
->value
;
74 strbuf_setlen(buf
, 0);
76 strbuf_addf(buf
, "%s%s", buf
->len
? "\n\n" : "", arg
);
79 return error("switch `m' requires a value");
83 static struct strategy
*get_strategy(const char *name
)
87 static struct cmdnames main_cmds
, other_cmds
;
93 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
94 if (!strcmp(name
, all_strategy
[i
].name
))
95 return &all_strategy
[i
];
98 struct cmdnames not_strategies
;
101 memset(¬_strategies
, 0, sizeof(struct cmdnames
));
102 load_command_list("git-merge-", &main_cmds
, &other_cmds
);
103 for (i
= 0; i
< main_cmds
.cnt
; i
++) {
105 struct cmdname
*ent
= main_cmds
.names
[i
];
106 for (j
= 0; j
< ARRAY_SIZE(all_strategy
); j
++)
107 if (!strncmp(ent
->name
, all_strategy
[j
].name
, ent
->len
)
108 && !all_strategy
[j
].name
[ent
->len
])
111 add_cmdname(¬_strategies
, ent
->name
, ent
->len
);
113 exclude_cmds(&main_cmds
, ¬_strategies
);
115 if (!is_in_cmdlist(&main_cmds
, name
) && !is_in_cmdlist(&other_cmds
, name
)) {
116 fprintf(stderr
, "Could not find merge strategy '%s'.\n", name
);
117 fprintf(stderr
, "Available strategies are:");
118 for (i
= 0; i
< main_cmds
.cnt
; i
++)
119 fprintf(stderr
, " %s", main_cmds
.names
[i
]->name
);
120 fprintf(stderr
, ".\n");
121 if (other_cmds
.cnt
) {
122 fprintf(stderr
, "Available custom strategies are:");
123 for (i
= 0; i
< other_cmds
.cnt
; i
++)
124 fprintf(stderr
, " %s", other_cmds
.names
[i
]->name
);
125 fprintf(stderr
, ".\n");
130 ret
= xcalloc(1, sizeof(struct strategy
));
131 ret
->name
= xstrdup(name
);
135 static void append_strategy(struct strategy
*s
)
137 ALLOC_GROW(use_strategies
, use_strategies_nr
+ 1, use_strategies_alloc
);
138 use_strategies
[use_strategies_nr
++] = s
;
141 static int option_parse_strategy(const struct option
*opt
,
142 const char *name
, int unset
)
147 append_strategy(get_strategy(name
));
151 static int option_parse_n(const struct option
*opt
,
152 const char *arg
, int unset
)
154 show_diffstat
= unset
;
158 static struct option builtin_merge_options
[] = {
159 { OPTION_CALLBACK
, 'n', NULL
, NULL
, NULL
,
160 "do not show a diffstat at the end of the merge",
161 PARSE_OPT_NOARG
, option_parse_n
},
162 OPT_BOOLEAN(0, "stat", &show_diffstat
,
163 "show a diffstat at the end of the merge"),
164 OPT_BOOLEAN(0, "summary", &show_diffstat
, "(synonym to --stat)"),
165 OPT_BOOLEAN(0, "log", &option_log
,
166 "add list of one-line log to merge commit message"),
167 OPT_BOOLEAN(0, "squash", &squash
,
168 "create a single commit instead of doing a merge"),
169 OPT_BOOLEAN(0, "commit", &option_commit
,
170 "perform a commit if the merge succeeds (default)"),
171 OPT_BOOLEAN(0, "ff", &allow_fast_forward
,
172 "allow fast-forward (default)"),
173 OPT_BOOLEAN(0, "ff-only", &fast_forward_only
,
174 "abort if fast-forward is not possible"),
175 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto
),
176 OPT_CALLBACK('s', "strategy", &use_strategies
, "strategy",
177 "merge strategy to use", option_parse_strategy
),
178 OPT_CALLBACK('m', "message", &merge_msg
, "message",
179 "message to be used for the merge commit (if any)",
180 option_parse_message
),
181 OPT__VERBOSITY(&verbosity
),
185 /* Cleans up metadata that is uninteresting after a succeeded merge. */
186 static void drop_save(void)
188 unlink(git_path("MERGE_HEAD"));
189 unlink(git_path("MERGE_MSG"));
190 unlink(git_path("MERGE_MODE"));
193 static void save_state(void)
196 struct child_process cp
;
197 struct strbuf buffer
= STRBUF_INIT
;
198 const char *argv
[] = {"stash", "create", NULL
};
200 memset(&cp
, 0, sizeof(cp
));
205 if (start_command(&cp
))
206 die("could not run stash.");
207 len
= strbuf_read(&buffer
, cp
.out
, 1024);
210 if (finish_command(&cp
) || len
< 0)
214 strbuf_setlen(&buffer
, buffer
.len
-1);
215 if (get_sha1(buffer
.buf
, stash
))
216 die("not a valid object: %s", buffer
.buf
);
219 static void reset_hard(unsigned const char *sha1
, int verbose
)
224 args
[i
++] = "read-tree";
227 args
[i
++] = "--reset";
229 args
[i
++] = sha1_to_hex(sha1
);
232 if (run_command_v_opt(args
, RUN_GIT_CMD
))
233 die("read-tree failed");
236 static void restore_state(void)
238 struct strbuf sb
= STRBUF_INIT
;
239 const char *args
[] = { "stash", "apply", NULL
, NULL
};
241 if (is_null_sha1(stash
))
246 args
[2] = sha1_to_hex(stash
);
249 * It is OK to ignore error here, for example when there was
250 * nothing to restore.
252 run_command_v_opt(args
, RUN_GIT_CMD
);
255 refresh_cache(REFRESH_QUIET
);
258 /* This is called when no merge was necessary. */
259 static void finish_up_to_date(const char *msg
)
262 printf("%s%s\n", squash
? " (nothing to squash)" : "", msg
);
266 static void squash_message(void)
269 struct commit
*commit
;
270 struct strbuf out
= STRBUF_INIT
;
271 struct commit_list
*j
;
273 struct pretty_print_context ctx
= {0};
275 printf("Squash commit -- not updating HEAD\n");
276 fd
= open(git_path("SQUASH_MSG"), O_WRONLY
| O_CREAT
, 0666);
278 die_errno("Could not write to '%s'", git_path("SQUASH_MSG"));
280 init_revisions(&rev
, NULL
);
281 rev
.ignore_merges
= 1;
282 rev
.commit_format
= CMIT_FMT_MEDIUM
;
284 commit
= lookup_commit(head
);
285 commit
->object
.flags
|= UNINTERESTING
;
286 add_pending_object(&rev
, &commit
->object
, NULL
);
288 for (j
= remoteheads
; j
; j
= j
->next
)
289 add_pending_object(&rev
, &j
->item
->object
, NULL
);
291 setup_revisions(0, NULL
, &rev
, NULL
);
292 if (prepare_revision_walk(&rev
))
293 die("revision walk setup failed");
295 ctx
.abbrev
= rev
.abbrev
;
296 ctx
.date_mode
= rev
.date_mode
;
298 strbuf_addstr(&out
, "Squashed commit of the following:\n");
299 while ((commit
= get_revision(&rev
)) != NULL
) {
300 strbuf_addch(&out
, '\n');
301 strbuf_addf(&out
, "commit %s\n",
302 sha1_to_hex(commit
->object
.sha1
));
303 pretty_print_commit(rev
.commit_format
, commit
, &out
, &ctx
);
305 if (write(fd
, out
.buf
, out
.len
) < 0)
306 die_errno("Writing SQUASH_MSG");
308 die_errno("Finishing SQUASH_MSG");
309 strbuf_release(&out
);
312 static void finish(const unsigned char *new_head
, const char *msg
)
314 struct strbuf reflog_message
= STRBUF_INIT
;
317 strbuf_addstr(&reflog_message
, getenv("GIT_REFLOG_ACTION"));
321 strbuf_addf(&reflog_message
, "%s: %s",
322 getenv("GIT_REFLOG_ACTION"), msg
);
327 if (verbosity
>= 0 && !merge_msg
.len
)
328 printf("No merge message -- not updating HEAD\n");
330 const char *argv_gc_auto
[] = { "gc", "--auto", NULL
};
331 update_ref(reflog_message
.buf
, "HEAD",
335 * We ignore errors in 'gc --auto', since the
336 * user should see them.
338 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
341 if (new_head
&& show_diffstat
) {
342 struct diff_options opts
;
344 opts
.output_format
|=
345 DIFF_FORMAT_SUMMARY
| DIFF_FORMAT_DIFFSTAT
;
346 opts
.detect_rename
= DIFF_DETECT_RENAME
;
347 if (diff_use_color_default
> 0)
348 DIFF_OPT_SET(&opts
, COLOR_DIFF
);
349 if (diff_setup_done(&opts
) < 0)
350 die("diff_setup_done failed");
351 diff_tree_sha1(head
, new_head
, "", &opts
);
356 /* Run a post-merge hook */
357 run_hook(NULL
, "post-merge", squash
? "1" : "0", NULL
);
359 strbuf_release(&reflog_message
);
362 /* Get the name for the merge commit's message. */
363 static void merge_name(const char *remote
, struct strbuf
*msg
)
365 struct object
*remote_head
;
366 unsigned char branch_head
[20], buf_sha
[20];
367 struct strbuf buf
= STRBUF_INIT
;
368 struct strbuf bname
= STRBUF_INIT
;
373 strbuf_branchname(&bname
, remote
);
376 memset(branch_head
, 0, sizeof(branch_head
));
377 remote_head
= peel_to_type(remote
, 0, NULL
, OBJ_COMMIT
);
379 die("'%s' does not point to a commit", remote
);
381 if (dwim_ref(remote
, strlen(remote
), branch_head
, &found_ref
) > 0) {
382 if (!prefixcmp(found_ref
, "refs/heads/")) {
383 strbuf_addf(msg
, "%s\t\tbranch '%s' of .\n",
384 sha1_to_hex(branch_head
), remote
);
387 if (!prefixcmp(found_ref
, "refs/remotes/")) {
388 strbuf_addf(msg
, "%s\t\tremote branch '%s' of .\n",
389 sha1_to_hex(branch_head
), remote
);
394 /* See if remote matches <name>^^^.. or <name>~<number> */
395 for (len
= 0, ptr
= remote
+ strlen(remote
);
396 remote
< ptr
&& ptr
[-1] == '^';
403 ptr
= strrchr(remote
, '~');
405 int seen_nonzero
= 0;
408 while (*++ptr
&& isdigit(*ptr
)) {
409 seen_nonzero
|= (*ptr
!= '0');
413 len
= 0; /* not ...~<number> */
414 else if (seen_nonzero
)
417 early
= 1; /* "name~" is "name~1"! */
421 struct strbuf truname
= STRBUF_INIT
;
422 strbuf_addstr(&truname
, "refs/heads/");
423 strbuf_addstr(&truname
, remote
);
424 strbuf_setlen(&truname
, truname
.len
- len
);
425 if (resolve_ref(truname
.buf
, buf_sha
, 0, NULL
)) {
427 "%s\t\tbranch '%s'%s of .\n",
428 sha1_to_hex(remote_head
->sha1
),
430 (early
? " (early part)" : ""));
431 strbuf_release(&truname
);
436 if (!strcmp(remote
, "FETCH_HEAD") &&
437 !access(git_path("FETCH_HEAD"), R_OK
)) {
439 struct strbuf line
= STRBUF_INIT
;
442 fp
= fopen(git_path("FETCH_HEAD"), "r");
444 die_errno("could not open '%s' for reading",
445 git_path("FETCH_HEAD"));
446 strbuf_getline(&line
, fp
, '\n');
448 ptr
= strstr(line
.buf
, "\tnot-for-merge\t");
450 strbuf_remove(&line
, ptr
-line
.buf
+1, 13);
451 strbuf_addbuf(msg
, &line
);
452 strbuf_release(&line
);
455 strbuf_addf(msg
, "%s\t\tcommit '%s'\n",
456 sha1_to_hex(remote_head
->sha1
), remote
);
458 strbuf_release(&buf
);
459 strbuf_release(&bname
);
462 static int git_merge_config(const char *k
, const char *v
, void *cb
)
464 if (branch
&& !prefixcmp(k
, "branch.") &&
465 !prefixcmp(k
+ 7, branch
) &&
466 !strcmp(k
+ 7 + strlen(branch
), ".mergeoptions")) {
472 argc
= split_cmdline(buf
, &argv
);
474 die("Bad branch.%s.mergeoptions string", branch
);
475 argv
= xrealloc(argv
, sizeof(*argv
) * (argc
+ 2));
476 memmove(argv
+ 1, argv
, sizeof(*argv
) * (argc
+ 1));
478 parse_options(argc
, argv
, NULL
, builtin_merge_options
,
479 builtin_merge_usage
, 0);
483 if (!strcmp(k
, "merge.diffstat") || !strcmp(k
, "merge.stat"))
484 show_diffstat
= git_config_bool(k
, v
);
485 else if (!strcmp(k
, "pull.twohead"))
486 return git_config_string(&pull_twohead
, k
, v
);
487 else if (!strcmp(k
, "pull.octopus"))
488 return git_config_string(&pull_octopus
, k
, v
);
489 else if (!strcmp(k
, "merge.log") || !strcmp(k
, "merge.summary"))
490 option_log
= git_config_bool(k
, v
);
491 return git_diff_ui_config(k
, v
, cb
);
494 static int read_tree_trivial(unsigned char *common
, unsigned char *head
,
498 struct tree
*trees
[MAX_UNPACK_TREES
];
499 struct tree_desc t
[MAX_UNPACK_TREES
];
500 struct unpack_trees_options opts
;
502 memset(&opts
, 0, sizeof(opts
));
504 opts
.src_index
= &the_index
;
505 opts
.dst_index
= &the_index
;
507 opts
.verbose_update
= 1;
508 opts
.trivial_merges_only
= 1;
510 trees
[nr_trees
] = parse_tree_indirect(common
);
511 if (!trees
[nr_trees
++])
513 trees
[nr_trees
] = parse_tree_indirect(head
);
514 if (!trees
[nr_trees
++])
516 trees
[nr_trees
] = parse_tree_indirect(one
);
517 if (!trees
[nr_trees
++])
519 opts
.fn
= threeway_merge
;
520 cache_tree_free(&active_cache_tree
);
521 for (i
= 0; i
< nr_trees
; i
++) {
522 parse_tree(trees
[i
]);
523 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
525 if (unpack_trees(nr_trees
, t
, &opts
))
530 static void write_tree_trivial(unsigned char *sha1
)
532 if (write_cache_as_tree(sha1
, 0, NULL
))
533 die("git write-tree failed to write a tree");
536 static int try_merge_strategy(const char *strategy
, struct commit_list
*common
,
537 const char *head_arg
)
541 struct commit_list
*j
;
542 struct strbuf buf
= STRBUF_INIT
;
544 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
546 index_fd
= hold_locked_index(lock
, 1);
547 refresh_cache(REFRESH_QUIET
);
548 if (active_cache_changed
&&
549 (write_cache(index_fd
, active_cache
, active_nr
) ||
550 commit_locked_index(lock
)))
551 return error("Unable to write index.");
552 rollback_lock_file(lock
);
554 if (!strcmp(strategy
, "recursive") || !strcmp(strategy
, "subtree")) {
556 struct commit
*result
;
557 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
559 struct commit_list
*reversed
= NULL
;
560 struct merge_options o
;
562 if (remoteheads
->next
) {
563 error("Not handling anything other than two heads merge.");
567 init_merge_options(&o
);
568 if (!strcmp(strategy
, "subtree"))
571 o
.branch1
= head_arg
;
572 o
.branch2
= remoteheads
->item
->util
;
574 for (j
= common
; j
; j
= j
->next
)
575 commit_list_insert(j
->item
, &reversed
);
577 index_fd
= hold_locked_index(lock
, 1);
578 clean
= merge_recursive(&o
, lookup_commit(head
),
579 remoteheads
->item
, reversed
, &result
);
580 if (active_cache_changed
&&
581 (write_cache(index_fd
, active_cache
, active_nr
) ||
582 commit_locked_index(lock
)))
583 die ("unable to write %s", get_index_file());
584 rollback_lock_file(lock
);
585 return clean
? 0 : 1;
587 args
= xmalloc((4 + commit_list_count(common
) +
588 commit_list_count(remoteheads
)) * sizeof(char *));
589 strbuf_addf(&buf
, "merge-%s", strategy
);
591 for (j
= common
; j
; j
= j
->next
)
592 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
594 args
[i
++] = head_arg
;
595 for (j
= remoteheads
; j
; j
= j
->next
)
596 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
598 ret
= run_command_v_opt(args
, RUN_GIT_CMD
);
599 strbuf_release(&buf
);
601 for (j
= common
; j
; j
= j
->next
)
602 free((void *)args
[i
++]);
604 for (j
= remoteheads
; j
; j
= j
->next
)
605 free((void *)args
[i
++]);
608 if (read_cache() < 0)
609 die("failed to read the cache");
610 resolve_undo_clear();
615 static void count_diff_files(struct diff_queue_struct
*q
,
616 struct diff_options
*opt
, void *data
)
623 static int count_unmerged_entries(void)
627 for (i
= 0; i
< active_nr
; i
++)
628 if (ce_stage(active_cache
[i
]))
634 static int checkout_fast_forward(unsigned char *head
, unsigned char *remote
)
636 struct tree
*trees
[MAX_UNPACK_TREES
];
637 struct unpack_trees_options opts
;
638 struct tree_desc t
[MAX_UNPACK_TREES
];
639 int i
, fd
, nr_trees
= 0;
640 struct dir_struct dir
;
641 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
643 refresh_cache(REFRESH_QUIET
);
645 fd
= hold_locked_index(lock_file
, 1);
647 memset(&trees
, 0, sizeof(trees
));
648 memset(&opts
, 0, sizeof(opts
));
649 memset(&t
, 0, sizeof(t
));
650 memset(&dir
, 0, sizeof(dir
));
651 dir
.flags
|= DIR_SHOW_IGNORED
;
652 dir
.exclude_per_dir
= ".gitignore";
656 opts
.src_index
= &the_index
;
657 opts
.dst_index
= &the_index
;
659 opts
.verbose_update
= 1;
661 opts
.fn
= twoway_merge
;
662 opts
.msgs
= get_porcelain_error_msgs();
664 trees
[nr_trees
] = parse_tree_indirect(head
);
665 if (!trees
[nr_trees
++])
667 trees
[nr_trees
] = parse_tree_indirect(remote
);
668 if (!trees
[nr_trees
++])
670 for (i
= 0; i
< nr_trees
; i
++) {
671 parse_tree(trees
[i
]);
672 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
674 if (unpack_trees(nr_trees
, t
, &opts
))
676 if (write_cache(fd
, active_cache
, active_nr
) ||
677 commit_locked_index(lock_file
))
678 die("unable to write new index file");
682 static void split_merge_strategies(const char *string
, struct strategy
**list
,
690 buf
= xstrdup(string
);
695 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
696 (*list
)[(*nr
)++].name
= xstrdup(q
);
701 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
702 (*list
)[(*nr
)++].name
= xstrdup(q
);
708 static void add_strategies(const char *string
, unsigned attr
)
710 struct strategy
*list
= NULL
;
711 int list_alloc
= 0, list_nr
= 0, i
;
713 memset(&list
, 0, sizeof(list
));
714 split_merge_strategies(string
, &list
, &list_nr
, &list_alloc
);
716 for (i
= 0; i
< list_nr
; i
++)
717 append_strategy(get_strategy(list
[i
].name
));
720 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
721 if (all_strategy
[i
].attr
& attr
)
722 append_strategy(&all_strategy
[i
]);
726 static int merge_trivial(void)
728 unsigned char result_tree
[20], result_commit
[20];
729 struct commit_list
*parent
= xmalloc(sizeof(*parent
));
731 write_tree_trivial(result_tree
);
732 printf("Wonderful.\n");
733 parent
->item
= lookup_commit(head
);
734 parent
->next
= xmalloc(sizeof(*parent
->next
));
735 parent
->next
->item
= remoteheads
->item
;
736 parent
->next
->next
= NULL
;
737 commit_tree(merge_msg
.buf
, result_tree
, parent
, result_commit
, NULL
);
738 finish(result_commit
, "In-index merge");
743 static int finish_automerge(struct commit_list
*common
,
744 unsigned char *result_tree
,
745 const char *wt_strategy
)
747 struct commit_list
*parents
= NULL
, *j
;
748 struct strbuf buf
= STRBUF_INIT
;
749 unsigned char result_commit
[20];
751 free_commit_list(common
);
752 if (allow_fast_forward
) {
753 parents
= remoteheads
;
754 commit_list_insert(lookup_commit(head
), &parents
);
755 parents
= reduce_heads(parents
);
757 struct commit_list
**pptr
= &parents
;
759 pptr
= &commit_list_insert(lookup_commit(head
),
761 for (j
= remoteheads
; j
; j
= j
->next
)
762 pptr
= &commit_list_insert(j
->item
, pptr
)->next
;
764 free_commit_list(remoteheads
);
765 strbuf_addch(&merge_msg
, '\n');
766 commit_tree(merge_msg
.buf
, result_tree
, parents
, result_commit
, NULL
);
767 strbuf_addf(&buf
, "Merge made by %s.", wt_strategy
);
768 finish(result_commit
, buf
.buf
);
769 strbuf_release(&buf
);
774 static int suggest_conflicts(void)
779 fp
= fopen(git_path("MERGE_MSG"), "a");
781 die_errno("Could not open '%s' for writing",
782 git_path("MERGE_MSG"));
783 fprintf(fp
, "\nConflicts:\n");
784 for (pos
= 0; pos
< active_nr
; pos
++) {
785 struct cache_entry
*ce
= active_cache
[pos
];
788 fprintf(fp
, "\t%s\n", ce
->name
);
789 while (pos
+ 1 < active_nr
&&
791 active_cache
[pos
+ 1]->name
))
796 rerere(allow_rerere_auto
);
797 printf("Automatic merge failed; "
798 "fix conflicts and then commit the result.\n");
802 static struct commit
*is_old_style_invocation(int argc
, const char **argv
)
804 struct commit
*second_token
= NULL
;
806 unsigned char second_sha1
[20];
808 if (get_sha1(argv
[1], second_sha1
))
810 second_token
= lookup_commit_reference_gently(second_sha1
, 0);
812 die("'%s' is not a commit", argv
[1]);
813 if (hashcmp(second_token
->object
.sha1
, head
))
819 static int evaluate_result(void)
824 /* Check how many files differ. */
825 init_revisions(&rev
, "");
826 setup_revisions(0, NULL
, &rev
, NULL
);
827 rev
.diffopt
.output_format
|=
828 DIFF_FORMAT_CALLBACK
;
829 rev
.diffopt
.format_callback
= count_diff_files
;
830 rev
.diffopt
.format_callback_data
= &cnt
;
831 run_diff_files(&rev
, 0);
834 * Check how many unmerged entries are
837 cnt
+= count_unmerged_entries();
842 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
844 unsigned char result_tree
[20];
845 struct strbuf buf
= STRBUF_INIT
;
846 const char *head_arg
;
847 int flag
, head_invalid
= 0, i
;
848 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
849 struct commit_list
*common
= NULL
;
850 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
851 struct commit_list
**remotes
= &remoteheads
;
853 if (read_cache_unmerged()) {
854 die_resolve_conflict("merge");
856 if (file_exists(git_path("MERGE_HEAD"))) {
858 * There is no unmerged entry, don't advise 'git
859 * add/rm <file>', just 'git commit'.
861 if (advice_resolve_conflict
)
862 die("You have not concluded your merge (MERGE_HEAD exists).\n"
863 "Please, commit your changes before you can merge.");
865 die("You have not concluded your merge (MERGE_HEAD exists).");
868 resolve_undo_clear();
870 * Check if we are _not_ on a detached HEAD, i.e. if there is a
873 branch
= resolve_ref("HEAD", head
, 0, &flag
);
874 if (branch
&& !prefixcmp(branch
, "refs/heads/"))
876 if (is_null_sha1(head
))
879 git_config(git_merge_config
, NULL
);
882 if (diff_use_color_default
== -1)
883 diff_use_color_default
= git_use_color_default
;
885 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
886 builtin_merge_usage
, 0);
891 if (!allow_fast_forward
)
892 die("You cannot combine --squash with --no-ff.");
896 if (!allow_fast_forward
&& fast_forward_only
)
897 die("You cannot combine --no-ff with --ff-only.");
900 usage_with_options(builtin_merge_usage
,
901 builtin_merge_options
);
904 * This could be traditional "merge <msg> HEAD <commit>..." and
905 * the way we can tell it is to see if the second token is HEAD,
906 * but some people might have misused the interface and used a
907 * committish that is the same as HEAD there instead.
908 * Traditional format never would have "-m" so it is an
909 * additional safety measure to check for it.
912 if (!have_message
&& is_old_style_invocation(argc
, argv
)) {
913 strbuf_addstr(&merge_msg
, argv
[0]);
917 } else if (head_invalid
) {
918 struct object
*remote_head
;
920 * If the merged head is a valid one there is no reason
921 * to forbid "git merge" into a branch yet to be born.
922 * We do the same for "git pull".
925 die("Can merge only exactly one commit into "
928 die("Squash commit into empty head not supported yet");
929 if (!allow_fast_forward
)
930 die("Non-fast-forward commit does not make sense into "
932 remote_head
= peel_to_type(argv
[0], 0, NULL
, OBJ_COMMIT
);
934 die("%s - not something we can merge", argv
[0]);
935 update_ref("initial pull", "HEAD", remote_head
->sha1
, NULL
, 0,
937 reset_hard(remote_head
->sha1
, 0);
940 struct strbuf msg
= STRBUF_INIT
;
942 /* We are invoked directly as the first-class UI. */
946 * All the rest are the commits being merged;
947 * prepare the standard merge summary message to
948 * be appended to the given message. If remote
949 * is invalid we will die later in the common
950 * codepath so we discard the error in this
954 for (i
= 0; i
< argc
; i
++)
955 merge_name(argv
[i
], &msg
);
956 fmt_merge_msg(option_log
, &msg
, &merge_msg
);
958 strbuf_setlen(&merge_msg
, merge_msg
.len
-1);
962 if (head_invalid
|| !argc
)
963 usage_with_options(builtin_merge_usage
,
964 builtin_merge_options
);
966 strbuf_addstr(&buf
, "merge");
967 for (i
= 0; i
< argc
; i
++)
968 strbuf_addf(&buf
, " %s", argv
[i
]);
969 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
972 for (i
= 0; i
< argc
; i
++) {
974 struct commit
*commit
;
976 o
= peel_to_type(argv
[i
], 0, NULL
, OBJ_COMMIT
);
978 die("%s - not something we can merge", argv
[i
]);
979 commit
= lookup_commit(o
->sha1
);
980 commit
->util
= (void *)argv
[i
];
981 remotes
= &commit_list_insert(commit
, remotes
)->next
;
983 strbuf_addf(&buf
, "GITHEAD_%s", sha1_to_hex(o
->sha1
));
984 setenv(buf
.buf
, argv
[i
], 1);
988 if (!use_strategies
) {
989 if (!remoteheads
->next
)
990 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
992 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
995 for (i
= 0; i
< use_strategies_nr
; i
++) {
996 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
997 allow_fast_forward
= 0;
998 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
1002 if (!remoteheads
->next
)
1003 common
= get_merge_bases(lookup_commit(head
),
1004 remoteheads
->item
, 1);
1006 struct commit_list
*list
= remoteheads
;
1007 commit_list_insert(lookup_commit(head
), &list
);
1008 common
= get_octopus_merge_bases(list
);
1012 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head
, NULL
, 0,
1016 ; /* No common ancestors found. We need a real merge. */
1017 else if (!remoteheads
->next
&& !common
->next
&&
1018 common
->item
== remoteheads
->item
) {
1020 * If head can reach all the merge then we are up to date.
1021 * but first the most common case of merging one remote.
1023 finish_up_to_date("Already up-to-date.");
1025 } else if (allow_fast_forward
&& !remoteheads
->next
&&
1027 !hashcmp(common
->item
->object
.sha1
, head
)) {
1028 /* Again the most common case of merging one remote. */
1029 struct strbuf msg
= STRBUF_INIT
;
1033 strcpy(hex
, find_unique_abbrev(head
, DEFAULT_ABBREV
));
1036 printf("Updating %s..%s\n",
1038 find_unique_abbrev(remoteheads
->item
->object
.sha1
,
1040 strbuf_addstr(&msg
, "Fast-forward");
1043 " (no commit created; -m option ignored)");
1044 o
= peel_to_type(sha1_to_hex(remoteheads
->item
->object
.sha1
),
1045 0, NULL
, OBJ_COMMIT
);
1049 if (checkout_fast_forward(head
, remoteheads
->item
->object
.sha1
))
1052 finish(o
->sha1
, msg
.buf
);
1055 } else if (!remoteheads
->next
&& common
->next
)
1058 * We are not doing octopus and not fast-forward. Need
1061 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1063 * We are not doing octopus, not fast-forward, and have
1066 refresh_cache(REFRESH_QUIET
);
1067 if (allow_trivial
&& !fast_forward_only
) {
1068 /* See if it is really trivial. */
1069 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1070 printf("Trying really trivial in-index merge...\n");
1071 if (!read_tree_trivial(common
->item
->object
.sha1
,
1072 head
, remoteheads
->item
->object
.sha1
))
1073 return merge_trivial();
1078 * An octopus. If we can reach all the remote we are up
1082 struct commit_list
*j
;
1084 for (j
= remoteheads
; j
; j
= j
->next
) {
1085 struct commit_list
*common_one
;
1088 * Here we *have* to calculate the individual
1089 * merge_bases again, otherwise "git merge HEAD^
1090 * HEAD^^" would be missed.
1092 common_one
= get_merge_bases(lookup_commit(head
),
1094 if (hashcmp(common_one
->item
->object
.sha1
,
1095 j
->item
->object
.sha1
)) {
1101 finish_up_to_date("Already up-to-date. Yeeah!");
1106 if (fast_forward_only
)
1107 die("Not possible to fast-forward, aborting.");
1109 /* We are going to make a new commit. */
1110 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1113 * At this point, we need a real merge. No matter what strategy
1114 * we use, it would operate on the index, possibly affecting the
1115 * working tree, and when resolved cleanly, have the desired
1116 * tree in the index -- this means that the index must be in
1117 * sync with the head commit. The strategies are responsible
1120 if (use_strategies_nr
!= 1) {
1122 * Stash away the local changes so that we can try more
1127 memcpy(stash
, null_sha1
, 20);
1130 for (i
= 0; i
< use_strategies_nr
; i
++) {
1133 printf("Rewinding the tree to pristine...\n");
1136 if (use_strategies_nr
!= 1)
1137 printf("Trying merge strategy %s...\n",
1138 use_strategies
[i
]->name
);
1140 * Remember which strategy left the state in the working
1143 wt_strategy
= use_strategies
[i
]->name
;
1145 ret
= try_merge_strategy(use_strategies
[i
]->name
,
1147 if (!option_commit
&& !ret
) {
1150 * This is necessary here just to avoid writing
1151 * the tree, but later we will *not* exit with
1152 * status code 1 because merge_was_ok is set.
1159 * The backend exits with 1 when conflicts are
1160 * left to be resolved, with 2 when it does not
1161 * handle the given merge at all.
1164 int cnt
= evaluate_result();
1166 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1167 best_strategy
= use_strategies
[i
]->name
;
1177 /* Automerge succeeded. */
1178 write_tree_trivial(result_tree
);
1179 automerge_was_ok
= 1;
1184 * If we have a resulting tree, that means the strategy module
1185 * auto resolved the merge cleanly.
1187 if (automerge_was_ok
)
1188 return finish_automerge(common
, result_tree
, wt_strategy
);
1191 * Pick the result from the best strategy and have the user fix
1194 if (!best_strategy
) {
1196 if (use_strategies_nr
> 1)
1198 "No merge strategy handled the merge.\n");
1200 fprintf(stderr
, "Merge with strategy %s failed.\n",
1201 use_strategies
[0]->name
);
1203 } else if (best_strategy
== wt_strategy
)
1204 ; /* We already have its result in the working tree. */
1206 printf("Rewinding the tree to pristine...\n");
1208 printf("Using the %s to prepare resolving by hand.\n",
1210 try_merge_strategy(best_strategy
, common
, head_arg
);
1217 struct commit_list
*j
;
1219 for (j
= remoteheads
; j
; j
= j
->next
)
1220 strbuf_addf(&buf
, "%s\n",
1221 sha1_to_hex(j
->item
->object
.sha1
));
1222 fd
= open(git_path("MERGE_HEAD"), O_WRONLY
| O_CREAT
, 0666);
1224 die_errno("Could not open '%s' for writing",
1225 git_path("MERGE_HEAD"));
1226 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1227 die_errno("Could not write to '%s'", git_path("MERGE_HEAD"));
1229 strbuf_addch(&merge_msg
, '\n');
1230 fd
= open(git_path("MERGE_MSG"), O_WRONLY
| O_CREAT
, 0666);
1232 die_errno("Could not open '%s' for writing",
1233 git_path("MERGE_MSG"));
1234 if (write_in_full(fd
, merge_msg
.buf
, merge_msg
.len
) !=
1236 die_errno("Could not write to '%s'", git_path("MERGE_MSG"));
1238 fd
= open(git_path("MERGE_MODE"), O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
1240 die_errno("Could not open '%s' for writing",
1241 git_path("MERGE_MODE"));
1243 if (!allow_fast_forward
)
1244 strbuf_addf(&buf
, "no-ff");
1245 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1246 die_errno("Could not write to '%s'", git_path("MERGE_MODE"));
1251 fprintf(stderr
, "Automatic merge went well; "
1252 "stopped before committing as requested\n");
1255 return suggest_conflicts();