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, shortlog_len
, 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
;
57 static int option_renormalize
;
59 static int allow_rerere_auto
;
60 static int abort_current_merge
;
61 static int show_progress
= -1;
63 static struct strategy all_strategy
[] = {
64 { "recursive", DEFAULT_TWOHEAD
| NO_TRIVIAL
},
65 { "octopus", DEFAULT_OCTOPUS
},
67 { "ours", NO_FAST_FORWARD
| NO_TRIVIAL
},
68 { "subtree", NO_FAST_FORWARD
| NO_TRIVIAL
},
71 static const char *pull_twohead
, *pull_octopus
;
73 static int option_parse_message(const struct option
*opt
,
74 const char *arg
, int unset
)
76 struct strbuf
*buf
= opt
->value
;
79 strbuf_setlen(buf
, 0);
81 strbuf_addf(buf
, "%s%s", buf
->len
? "\n\n" : "", arg
);
84 return error(_("switch `m' requires a value"));
88 static struct strategy
*get_strategy(const char *name
)
92 static struct cmdnames main_cmds
, other_cmds
;
98 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
99 if (!strcmp(name
, all_strategy
[i
].name
))
100 return &all_strategy
[i
];
103 struct cmdnames not_strategies
;
106 memset(¬_strategies
, 0, sizeof(struct cmdnames
));
107 load_command_list("git-merge-", &main_cmds
, &other_cmds
);
108 for (i
= 0; i
< main_cmds
.cnt
; i
++) {
110 struct cmdname
*ent
= main_cmds
.names
[i
];
111 for (j
= 0; j
< ARRAY_SIZE(all_strategy
); j
++)
112 if (!strncmp(ent
->name
, all_strategy
[j
].name
, ent
->len
)
113 && !all_strategy
[j
].name
[ent
->len
])
116 add_cmdname(¬_strategies
, ent
->name
, ent
->len
);
118 exclude_cmds(&main_cmds
, ¬_strategies
);
120 if (!is_in_cmdlist(&main_cmds
, name
) && !is_in_cmdlist(&other_cmds
, name
)) {
121 fprintf(stderr
, _("Could not find merge strategy '%s'.\n"), name
);
122 fprintf(stderr
, _("Available strategies are:"));
123 for (i
= 0; i
< main_cmds
.cnt
; i
++)
124 fprintf(stderr
, " %s", main_cmds
.names
[i
]->name
);
125 fprintf(stderr
, ".\n");
126 if (other_cmds
.cnt
) {
127 fprintf(stderr
, _("Available custom strategies are:"));
128 for (i
= 0; i
< other_cmds
.cnt
; i
++)
129 fprintf(stderr
, " %s", other_cmds
.names
[i
]->name
);
130 fprintf(stderr
, ".\n");
135 ret
= xcalloc(1, sizeof(struct strategy
));
136 ret
->name
= xstrdup(name
);
137 ret
->attr
= NO_TRIVIAL
;
141 static void append_strategy(struct strategy
*s
)
143 ALLOC_GROW(use_strategies
, use_strategies_nr
+ 1, use_strategies_alloc
);
144 use_strategies
[use_strategies_nr
++] = s
;
147 static int option_parse_strategy(const struct option
*opt
,
148 const char *name
, int unset
)
153 append_strategy(get_strategy(name
));
157 static int option_parse_x(const struct option
*opt
,
158 const char *arg
, int unset
)
163 ALLOC_GROW(xopts
, xopts_nr
+ 1, xopts_alloc
);
164 xopts
[xopts_nr
++] = xstrdup(arg
);
168 static int option_parse_n(const struct option
*opt
,
169 const char *arg
, int unset
)
171 show_diffstat
= unset
;
175 static struct option builtin_merge_options
[] = {
176 { OPTION_CALLBACK
, 'n', NULL
, NULL
, NULL
,
177 "do not show a diffstat at the end of the merge",
178 PARSE_OPT_NOARG
, option_parse_n
},
179 OPT_BOOLEAN(0, "stat", &show_diffstat
,
180 "show a diffstat at the end of the merge"),
181 OPT_BOOLEAN(0, "summary", &show_diffstat
, "(synonym to --stat)"),
182 { OPTION_INTEGER
, 0, "log", &shortlog_len
, "n",
183 "add (at most <n>) entries from shortlog to merge commit message",
184 PARSE_OPT_OPTARG
, NULL
, DEFAULT_MERGE_LOG_LEN
},
185 OPT_BOOLEAN(0, "squash", &squash
,
186 "create a single commit instead of doing a merge"),
187 OPT_BOOLEAN(0, "commit", &option_commit
,
188 "perform a commit if the merge succeeds (default)"),
189 OPT_BOOLEAN(0, "ff", &allow_fast_forward
,
190 "allow fast-forward (default)"),
191 OPT_BOOLEAN(0, "ff-only", &fast_forward_only
,
192 "abort if fast-forward is not possible"),
193 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto
),
194 OPT_CALLBACK('s', "strategy", &use_strategies
, "strategy",
195 "merge strategy to use", option_parse_strategy
),
196 OPT_CALLBACK('X', "strategy-option", &xopts
, "option=value",
197 "option for selected merge strategy", option_parse_x
),
198 OPT_CALLBACK('m', "message", &merge_msg
, "message",
199 "merge commit message (for a non-fast-forward merge)",
200 option_parse_message
),
201 OPT__VERBOSITY(&verbosity
),
202 OPT_BOOLEAN(0, "abort", &abort_current_merge
,
203 "abort the current in-progress merge"),
204 OPT_SET_INT(0, "progress", &show_progress
, "force progress reporting", 1),
208 /* Cleans up metadata that is uninteresting after a succeeded merge. */
209 static void drop_save(void)
211 unlink(git_path("MERGE_HEAD"));
212 unlink(git_path("MERGE_MSG"));
213 unlink(git_path("MERGE_MODE"));
216 static void save_state(void)
219 struct child_process cp
;
220 struct strbuf buffer
= STRBUF_INIT
;
221 const char *argv
[] = {"stash", "create", NULL
};
223 memset(&cp
, 0, sizeof(cp
));
228 if (start_command(&cp
))
229 die(_("could not run stash."));
230 len
= strbuf_read(&buffer
, cp
.out
, 1024);
233 if (finish_command(&cp
) || len
< 0)
234 die(_("stash failed"));
237 strbuf_setlen(&buffer
, buffer
.len
-1);
238 if (get_sha1(buffer
.buf
, stash
))
239 die(_("not a valid object: %s"), buffer
.buf
);
242 static void read_empty(unsigned const char *sha1
, int verbose
)
247 args
[i
++] = "read-tree";
252 args
[i
++] = EMPTY_TREE_SHA1_HEX
;
253 args
[i
++] = sha1_to_hex(sha1
);
256 if (run_command_v_opt(args
, RUN_GIT_CMD
))
257 die(_("read-tree failed"));
260 static void reset_hard(unsigned const char *sha1
, int verbose
)
265 args
[i
++] = "read-tree";
268 args
[i
++] = "--reset";
270 args
[i
++] = sha1_to_hex(sha1
);
273 if (run_command_v_opt(args
, RUN_GIT_CMD
))
274 die(_("read-tree failed"));
277 static void restore_state(void)
279 struct strbuf sb
= STRBUF_INIT
;
280 const char *args
[] = { "stash", "apply", NULL
, NULL
};
282 if (is_null_sha1(stash
))
287 args
[2] = sha1_to_hex(stash
);
290 * It is OK to ignore error here, for example when there was
291 * nothing to restore.
293 run_command_v_opt(args
, RUN_GIT_CMD
);
296 refresh_cache(REFRESH_QUIET
);
299 /* This is called when no merge was necessary. */
300 static void finish_up_to_date(const char *msg
)
303 printf("%s%s\n", squash
? _(" (nothing to squash)") : "", msg
);
307 static void squash_message(void)
310 struct commit
*commit
;
311 struct strbuf out
= STRBUF_INIT
;
312 struct commit_list
*j
;
314 struct pretty_print_context ctx
= {0};
316 printf(_("Squash commit -- not updating HEAD\n"));
317 fd
= open(git_path("SQUASH_MSG"), O_WRONLY
| O_CREAT
, 0666);
319 die_errno(_("Could not write to '%s'"), git_path("SQUASH_MSG"));
321 init_revisions(&rev
, NULL
);
322 rev
.ignore_merges
= 1;
323 rev
.commit_format
= CMIT_FMT_MEDIUM
;
325 commit
= lookup_commit(head
);
326 commit
->object
.flags
|= UNINTERESTING
;
327 add_pending_object(&rev
, &commit
->object
, NULL
);
329 for (j
= remoteheads
; j
; j
= j
->next
)
330 add_pending_object(&rev
, &j
->item
->object
, NULL
);
332 setup_revisions(0, NULL
, &rev
, NULL
);
333 if (prepare_revision_walk(&rev
))
334 die(_("revision walk setup failed"));
336 ctx
.abbrev
= rev
.abbrev
;
337 ctx
.date_mode
= rev
.date_mode
;
339 strbuf_addstr(&out
, "Squashed commit of the following:\n");
340 while ((commit
= get_revision(&rev
)) != NULL
) {
341 strbuf_addch(&out
, '\n');
342 strbuf_addf(&out
, "commit %s\n",
343 sha1_to_hex(commit
->object
.sha1
));
344 pretty_print_commit(rev
.commit_format
, commit
, &out
, &ctx
);
346 if (write(fd
, out
.buf
, out
.len
) < 0)
347 die_errno(_("Writing SQUASH_MSG"));
349 die_errno(_("Finishing SQUASH_MSG"));
350 strbuf_release(&out
);
353 static void finish(const unsigned char *new_head
, const char *msg
)
355 struct strbuf reflog_message
= STRBUF_INIT
;
358 strbuf_addstr(&reflog_message
, getenv("GIT_REFLOG_ACTION"));
362 strbuf_addf(&reflog_message
, "%s: %s",
363 getenv("GIT_REFLOG_ACTION"), msg
);
368 if (verbosity
>= 0 && !merge_msg
.len
)
369 printf(_("No merge message -- not updating HEAD\n"));
371 const char *argv_gc_auto
[] = { "gc", "--auto", NULL
};
372 update_ref(reflog_message
.buf
, "HEAD",
376 * We ignore errors in 'gc --auto', since the
377 * user should see them.
379 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
382 if (new_head
&& show_diffstat
) {
383 struct diff_options opts
;
385 opts
.output_format
|=
386 DIFF_FORMAT_SUMMARY
| DIFF_FORMAT_DIFFSTAT
;
387 opts
.detect_rename
= DIFF_DETECT_RENAME
;
388 if (diff_use_color_default
> 0)
389 DIFF_OPT_SET(&opts
, COLOR_DIFF
);
390 if (diff_setup_done(&opts
) < 0)
391 die(_("diff_setup_done failed"));
392 diff_tree_sha1(head
, new_head
, "", &opts
);
397 /* Run a post-merge hook */
398 run_hook(NULL
, "post-merge", squash
? "1" : "0", NULL
);
400 strbuf_release(&reflog_message
);
403 /* Get the name for the merge commit's message. */
404 static void merge_name(const char *remote
, struct strbuf
*msg
)
406 struct object
*remote_head
;
407 unsigned char branch_head
[20], buf_sha
[20];
408 struct strbuf buf
= STRBUF_INIT
;
409 struct strbuf bname
= STRBUF_INIT
;
414 strbuf_branchname(&bname
, remote
);
417 memset(branch_head
, 0, sizeof(branch_head
));
418 remote_head
= peel_to_type(remote
, 0, NULL
, OBJ_COMMIT
);
420 die(_("'%s' does not point to a commit"), remote
);
422 if (dwim_ref(remote
, strlen(remote
), branch_head
, &found_ref
) > 0) {
423 if (!prefixcmp(found_ref
, "refs/heads/")) {
424 strbuf_addf(msg
, "%s\t\tbranch '%s' of .\n",
425 sha1_to_hex(branch_head
), remote
);
428 if (!prefixcmp(found_ref
, "refs/remotes/")) {
429 strbuf_addf(msg
, "%s\t\tremote-tracking branch '%s' of .\n",
430 sha1_to_hex(branch_head
), remote
);
435 /* See if remote matches <name>^^^.. or <name>~<number> */
436 for (len
= 0, ptr
= remote
+ strlen(remote
);
437 remote
< ptr
&& ptr
[-1] == '^';
444 ptr
= strrchr(remote
, '~');
446 int seen_nonzero
= 0;
449 while (*++ptr
&& isdigit(*ptr
)) {
450 seen_nonzero
|= (*ptr
!= '0');
454 len
= 0; /* not ...~<number> */
455 else if (seen_nonzero
)
458 early
= 1; /* "name~" is "name~1"! */
462 struct strbuf truname
= STRBUF_INIT
;
463 strbuf_addstr(&truname
, "refs/heads/");
464 strbuf_addstr(&truname
, remote
);
465 strbuf_setlen(&truname
, truname
.len
- len
);
466 if (resolve_ref(truname
.buf
, buf_sha
, 1, NULL
)) {
468 "%s\t\tbranch '%s'%s of .\n",
469 sha1_to_hex(remote_head
->sha1
),
471 (early
? " (early part)" : ""));
472 strbuf_release(&truname
);
477 if (!strcmp(remote
, "FETCH_HEAD") &&
478 !access(git_path("FETCH_HEAD"), R_OK
)) {
480 struct strbuf line
= STRBUF_INIT
;
483 fp
= fopen(git_path("FETCH_HEAD"), "r");
485 die_errno(_("could not open '%s' for reading"),
486 git_path("FETCH_HEAD"));
487 strbuf_getline(&line
, fp
, '\n');
489 ptr
= strstr(line
.buf
, "\tnot-for-merge\t");
491 strbuf_remove(&line
, ptr
-line
.buf
+1, 13);
492 strbuf_addbuf(msg
, &line
);
493 strbuf_release(&line
);
496 strbuf_addf(msg
, "%s\t\tcommit '%s'\n",
497 sha1_to_hex(remote_head
->sha1
), remote
);
499 strbuf_release(&buf
);
500 strbuf_release(&bname
);
503 static int git_merge_config(const char *k
, const char *v
, void *cb
)
505 if (branch
&& !prefixcmp(k
, "branch.") &&
506 !prefixcmp(k
+ 7, branch
) &&
507 !strcmp(k
+ 7 + strlen(branch
), ".mergeoptions")) {
513 argc
= split_cmdline(buf
, &argv
);
515 die(_("Bad branch.%s.mergeoptions string: %s"), branch
,
516 split_cmdline_strerror(argc
));
517 argv
= xrealloc(argv
, sizeof(*argv
) * (argc
+ 2));
518 memmove(argv
+ 1, argv
, sizeof(*argv
) * (argc
+ 1));
520 parse_options(argc
, argv
, NULL
, builtin_merge_options
,
521 builtin_merge_usage
, 0);
525 if (!strcmp(k
, "merge.diffstat") || !strcmp(k
, "merge.stat"))
526 show_diffstat
= git_config_bool(k
, v
);
527 else if (!strcmp(k
, "pull.twohead"))
528 return git_config_string(&pull_twohead
, k
, v
);
529 else if (!strcmp(k
, "pull.octopus"))
530 return git_config_string(&pull_octopus
, k
, v
);
531 else if (!strcmp(k
, "merge.renormalize"))
532 option_renormalize
= git_config_bool(k
, v
);
533 else if (!strcmp(k
, "merge.log") || !strcmp(k
, "merge.summary")) {
535 shortlog_len
= git_config_bool_or_int(k
, v
, &is_bool
);
536 if (!is_bool
&& shortlog_len
< 0)
537 return error(_("%s: negative length %s"), k
, v
);
538 if (is_bool
&& shortlog_len
)
539 shortlog_len
= DEFAULT_MERGE_LOG_LEN
;
542 return git_diff_ui_config(k
, v
, cb
);
545 static int read_tree_trivial(unsigned char *common
, unsigned char *head
,
549 struct tree
*trees
[MAX_UNPACK_TREES
];
550 struct tree_desc t
[MAX_UNPACK_TREES
];
551 struct unpack_trees_options opts
;
553 memset(&opts
, 0, sizeof(opts
));
555 opts
.src_index
= &the_index
;
556 opts
.dst_index
= &the_index
;
558 opts
.verbose_update
= 1;
559 opts
.trivial_merges_only
= 1;
561 trees
[nr_trees
] = parse_tree_indirect(common
);
562 if (!trees
[nr_trees
++])
564 trees
[nr_trees
] = parse_tree_indirect(head
);
565 if (!trees
[nr_trees
++])
567 trees
[nr_trees
] = parse_tree_indirect(one
);
568 if (!trees
[nr_trees
++])
570 opts
.fn
= threeway_merge
;
571 cache_tree_free(&active_cache_tree
);
572 for (i
= 0; i
< nr_trees
; i
++) {
573 parse_tree(trees
[i
]);
574 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
576 if (unpack_trees(nr_trees
, t
, &opts
))
581 static void write_tree_trivial(unsigned char *sha1
)
583 if (write_cache_as_tree(sha1
, 0, NULL
))
584 die(_("git write-tree failed to write a tree"));
587 int try_merge_command(const char *strategy
, size_t xopts_nr
,
588 const char **xopts
, struct commit_list
*common
,
589 const char *head_arg
, struct commit_list
*remotes
)
592 int i
= 0, x
= 0, ret
;
593 struct commit_list
*j
;
594 struct strbuf buf
= STRBUF_INIT
;
596 args
= xmalloc((4 + xopts_nr
+ commit_list_count(common
) +
597 commit_list_count(remotes
)) * sizeof(char *));
598 strbuf_addf(&buf
, "merge-%s", strategy
);
600 for (x
= 0; x
< xopts_nr
; x
++) {
601 char *s
= xmalloc(strlen(xopts
[x
])+2+1);
603 strcpy(s
+2, xopts
[x
]);
606 for (j
= common
; j
; j
= j
->next
)
607 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
609 args
[i
++] = head_arg
;
610 for (j
= remotes
; j
; j
= j
->next
)
611 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
613 ret
= run_command_v_opt(args
, RUN_GIT_CMD
);
614 strbuf_release(&buf
);
616 for (x
= 0; x
< xopts_nr
; x
++)
617 free((void *)args
[i
++]);
618 for (j
= common
; j
; j
= j
->next
)
619 free((void *)args
[i
++]);
621 for (j
= remotes
; j
; j
= j
->next
)
622 free((void *)args
[i
++]);
625 if (read_cache() < 0)
626 die(_("failed to read the cache"));
627 resolve_undo_clear();
632 static int try_merge_strategy(const char *strategy
, struct commit_list
*common
,
633 const char *head_arg
)
636 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
638 index_fd
= hold_locked_index(lock
, 1);
639 refresh_cache(REFRESH_QUIET
);
640 if (active_cache_changed
&&
641 (write_cache(index_fd
, active_cache
, active_nr
) ||
642 commit_locked_index(lock
)))
643 return error(_("Unable to write index."));
644 rollback_lock_file(lock
);
646 if (!strcmp(strategy
, "recursive") || !strcmp(strategy
, "subtree")) {
648 struct commit
*result
;
649 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
651 struct commit_list
*reversed
= NULL
;
652 struct merge_options o
;
653 struct commit_list
*j
;
655 if (remoteheads
->next
) {
656 error(_("Not handling anything other than two heads merge."));
660 init_merge_options(&o
);
661 if (!strcmp(strategy
, "subtree"))
662 o
.subtree_shift
= "";
664 o
.renormalize
= option_renormalize
;
665 o
.show_rename_progress
=
666 show_progress
== -1 ? isatty(2) : show_progress
;
668 for (x
= 0; x
< xopts_nr
; x
++)
669 if (parse_merge_opt(&o
, xopts
[x
]))
670 die(_("Unknown option for merge-recursive: -X%s"), xopts
[x
]);
672 o
.branch1
= head_arg
;
673 o
.branch2
= remoteheads
->item
->util
;
675 for (j
= common
; j
; j
= j
->next
)
676 commit_list_insert(j
->item
, &reversed
);
678 index_fd
= hold_locked_index(lock
, 1);
679 clean
= merge_recursive(&o
, lookup_commit(head
),
680 remoteheads
->item
, reversed
, &result
);
681 if (active_cache_changed
&&
682 (write_cache(index_fd
, active_cache
, active_nr
) ||
683 commit_locked_index(lock
)))
684 die (_("unable to write %s"), get_index_file());
685 rollback_lock_file(lock
);
686 return clean
? 0 : 1;
688 return try_merge_command(strategy
, xopts_nr
, xopts
,
689 common
, head_arg
, remoteheads
);
693 static void count_diff_files(struct diff_queue_struct
*q
,
694 struct diff_options
*opt
, void *data
)
701 static int count_unmerged_entries(void)
705 for (i
= 0; i
< active_nr
; i
++)
706 if (ce_stage(active_cache
[i
]))
712 int checkout_fast_forward(const unsigned char *head
, const unsigned char *remote
)
714 struct tree
*trees
[MAX_UNPACK_TREES
];
715 struct unpack_trees_options opts
;
716 struct tree_desc t
[MAX_UNPACK_TREES
];
717 int i
, fd
, nr_trees
= 0;
718 struct dir_struct dir
;
719 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
721 refresh_cache(REFRESH_QUIET
);
723 fd
= hold_locked_index(lock_file
, 1);
725 memset(&trees
, 0, sizeof(trees
));
726 memset(&opts
, 0, sizeof(opts
));
727 memset(&t
, 0, sizeof(t
));
728 memset(&dir
, 0, sizeof(dir
));
729 dir
.flags
|= DIR_SHOW_IGNORED
;
730 dir
.exclude_per_dir
= ".gitignore";
734 opts
.src_index
= &the_index
;
735 opts
.dst_index
= &the_index
;
737 opts
.verbose_update
= 1;
739 opts
.fn
= twoway_merge
;
740 setup_unpack_trees_porcelain(&opts
, "merge");
742 trees
[nr_trees
] = parse_tree_indirect(head
);
743 if (!trees
[nr_trees
++])
745 trees
[nr_trees
] = parse_tree_indirect(remote
);
746 if (!trees
[nr_trees
++])
748 for (i
= 0; i
< nr_trees
; i
++) {
749 parse_tree(trees
[i
]);
750 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
752 if (unpack_trees(nr_trees
, t
, &opts
))
754 if (write_cache(fd
, active_cache
, active_nr
) ||
755 commit_locked_index(lock_file
))
756 die(_("unable to write new index file"));
760 static void split_merge_strategies(const char *string
, struct strategy
**list
,
768 buf
= xstrdup(string
);
773 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
774 (*list
)[(*nr
)++].name
= xstrdup(q
);
779 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
780 (*list
)[(*nr
)++].name
= xstrdup(q
);
786 static void add_strategies(const char *string
, unsigned attr
)
788 struct strategy
*list
= NULL
;
789 int list_alloc
= 0, list_nr
= 0, i
;
791 memset(&list
, 0, sizeof(list
));
792 split_merge_strategies(string
, &list
, &list_nr
, &list_alloc
);
794 for (i
= 0; i
< list_nr
; i
++)
795 append_strategy(get_strategy(list
[i
].name
));
798 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
799 if (all_strategy
[i
].attr
& attr
)
800 append_strategy(&all_strategy
[i
]);
804 static void write_merge_msg(void)
806 int fd
= open(git_path("MERGE_MSG"), O_WRONLY
| O_CREAT
, 0666);
808 die_errno(_("Could not open '%s' for writing"),
809 git_path("MERGE_MSG"));
810 if (write_in_full(fd
, merge_msg
.buf
, merge_msg
.len
) != merge_msg
.len
)
811 die_errno(_("Could not write to '%s'"), git_path("MERGE_MSG"));
815 static void read_merge_msg(void)
817 strbuf_reset(&merge_msg
);
818 if (strbuf_read_file(&merge_msg
, git_path("MERGE_MSG"), 0) < 0)
819 die_errno("Could not read from '%s'", git_path("MERGE_MSG"));
822 static void run_prepare_commit_msg(void)
825 run_hook(get_index_file(), "prepare-commit-msg",
826 git_path("MERGE_MSG"), "merge", NULL
, NULL
);
830 static int merge_trivial(void)
832 unsigned char result_tree
[20], result_commit
[20];
833 struct commit_list
*parent
= xmalloc(sizeof(*parent
));
835 write_tree_trivial(result_tree
);
836 printf(_("Wonderful.\n"));
837 parent
->item
= lookup_commit(head
);
838 parent
->next
= xmalloc(sizeof(*parent
->next
));
839 parent
->next
->item
= remoteheads
->item
;
840 parent
->next
->next
= NULL
;
841 run_prepare_commit_msg();
842 commit_tree(merge_msg
.buf
, result_tree
, parent
, result_commit
, NULL
);
843 finish(result_commit
, "In-index merge");
848 static int finish_automerge(struct commit_list
*common
,
849 unsigned char *result_tree
,
850 const char *wt_strategy
)
852 struct commit_list
*parents
= NULL
, *j
;
853 struct strbuf buf
= STRBUF_INIT
;
854 unsigned char result_commit
[20];
856 free_commit_list(common
);
857 if (allow_fast_forward
) {
858 parents
= remoteheads
;
859 commit_list_insert(lookup_commit(head
), &parents
);
860 parents
= reduce_heads(parents
);
862 struct commit_list
**pptr
= &parents
;
864 pptr
= &commit_list_insert(lookup_commit(head
),
866 for (j
= remoteheads
; j
; j
= j
->next
)
867 pptr
= &commit_list_insert(j
->item
, pptr
)->next
;
869 free_commit_list(remoteheads
);
870 strbuf_addch(&merge_msg
, '\n');
871 run_prepare_commit_msg();
872 commit_tree(merge_msg
.buf
, result_tree
, parents
, result_commit
, NULL
);
873 strbuf_addf(&buf
, "Merge made by %s.", wt_strategy
);
874 finish(result_commit
, buf
.buf
);
875 strbuf_release(&buf
);
880 static int suggest_conflicts(int renormalizing
)
885 fp
= fopen(git_path("MERGE_MSG"), "a");
887 die_errno(_("Could not open '%s' for writing"),
888 git_path("MERGE_MSG"));
889 fprintf(fp
, "\nConflicts:\n");
890 for (pos
= 0; pos
< active_nr
; pos
++) {
891 struct cache_entry
*ce
= active_cache
[pos
];
894 fprintf(fp
, "\t%s\n", ce
->name
);
895 while (pos
+ 1 < active_nr
&&
897 active_cache
[pos
+ 1]->name
))
902 rerere(allow_rerere_auto
);
903 printf(_("Automatic merge failed; "
904 "fix conflicts and then commit the result.\n"));
908 static struct commit
*is_old_style_invocation(int argc
, const char **argv
)
910 struct commit
*second_token
= NULL
;
912 unsigned char second_sha1
[20];
914 if (get_sha1(argv
[1], second_sha1
))
916 second_token
= lookup_commit_reference_gently(second_sha1
, 0);
918 die(_("'%s' is not a commit"), argv
[1]);
919 if (hashcmp(second_token
->object
.sha1
, head
))
925 static int evaluate_result(void)
930 /* Check how many files differ. */
931 init_revisions(&rev
, "");
932 setup_revisions(0, NULL
, &rev
, NULL
);
933 rev
.diffopt
.output_format
|=
934 DIFF_FORMAT_CALLBACK
;
935 rev
.diffopt
.format_callback
= count_diff_files
;
936 rev
.diffopt
.format_callback_data
= &cnt
;
937 run_diff_files(&rev
, 0);
940 * Check how many unmerged entries are
943 cnt
+= count_unmerged_entries();
948 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
950 unsigned char result_tree
[20];
951 struct strbuf buf
= STRBUF_INIT
;
952 const char *head_arg
;
953 int flag
, head_invalid
= 0, i
;
954 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
955 struct commit_list
*common
= NULL
;
956 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
957 struct commit_list
**remotes
= &remoteheads
;
959 if (argc
== 2 && !strcmp(argv
[1], "-h"))
960 usage_with_options(builtin_merge_usage
, builtin_merge_options
);
963 * Check if we are _not_ on a detached HEAD, i.e. if there is a
966 branch
= resolve_ref("HEAD", head
, 0, &flag
);
967 if (branch
&& !prefixcmp(branch
, "refs/heads/"))
969 if (is_null_sha1(head
))
972 git_config(git_merge_config
, NULL
);
975 if (diff_use_color_default
== -1)
976 diff_use_color_default
= git_use_color_default
;
978 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
979 builtin_merge_usage
, 0);
981 if (verbosity
< 0 && show_progress
== -1)
984 if (abort_current_merge
) {
986 const char *nargv
[] = {"reset", "--merge", NULL
};
988 if (!file_exists(git_path("MERGE_HEAD")))
989 die(_("There is no merge to abort (MERGE_HEAD missing)."));
991 /* Invoke 'git reset --merge' */
992 return cmd_reset(nargc
, nargv
, prefix
);
995 if (read_cache_unmerged())
996 die_resolve_conflict("merge");
998 if (file_exists(git_path("MERGE_HEAD"))) {
1000 * There is no unmerged entry, don't advise 'git
1001 * add/rm <file>', just 'git commit'.
1003 if (advice_resolve_conflict
)
1004 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1005 "Please, commit your changes before you can merge."));
1007 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1009 if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
1010 if (advice_resolve_conflict
)
1011 die("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1012 "Please, commit your changes before you can merge.");
1014 die("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).");
1016 resolve_undo_clear();
1022 if (!allow_fast_forward
)
1023 die(_("You cannot combine --squash with --no-ff."));
1027 if (!allow_fast_forward
&& fast_forward_only
)
1028 die(_("You cannot combine --no-ff with --ff-only."));
1031 usage_with_options(builtin_merge_usage
,
1032 builtin_merge_options
);
1035 * This could be traditional "merge <msg> HEAD <commit>..." and
1036 * the way we can tell it is to see if the second token is HEAD,
1037 * but some people might have misused the interface and used a
1038 * committish that is the same as HEAD there instead.
1039 * Traditional format never would have "-m" so it is an
1040 * additional safety measure to check for it.
1043 if (!have_message
&& is_old_style_invocation(argc
, argv
)) {
1044 strbuf_addstr(&merge_msg
, argv
[0]);
1048 } else if (head_invalid
) {
1049 struct object
*remote_head
;
1051 * If the merged head is a valid one there is no reason
1052 * to forbid "git merge" into a branch yet to be born.
1053 * We do the same for "git pull".
1056 die(_("Can merge only exactly one commit into "
1059 die(_("Squash commit into empty head not supported yet"));
1060 if (!allow_fast_forward
)
1061 die(_("Non-fast-forward commit does not make sense into "
1063 remote_head
= peel_to_type(argv
[0], 0, NULL
, OBJ_COMMIT
);
1065 die(_("%s - not something we can merge"), argv
[0]);
1066 update_ref("initial pull", "HEAD", remote_head
->sha1
, NULL
, 0,
1068 read_empty(remote_head
->sha1
, 0);
1071 struct strbuf merge_names
= STRBUF_INIT
;
1073 /* We are invoked directly as the first-class UI. */
1077 * All the rest are the commits being merged;
1078 * prepare the standard merge summary message to
1079 * be appended to the given message. If remote
1080 * is invalid we will die later in the common
1081 * codepath so we discard the error in this
1084 for (i
= 0; i
< argc
; i
++)
1085 merge_name(argv
[i
], &merge_names
);
1087 if (!have_message
|| shortlog_len
) {
1088 fmt_merge_msg(&merge_names
, &merge_msg
, !have_message
,
1091 strbuf_setlen(&merge_msg
, merge_msg
.len
- 1);
1095 if (head_invalid
|| !argc
)
1096 usage_with_options(builtin_merge_usage
,
1097 builtin_merge_options
);
1099 strbuf_addstr(&buf
, "merge");
1100 for (i
= 0; i
< argc
; i
++)
1101 strbuf_addf(&buf
, " %s", argv
[i
]);
1102 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
1105 for (i
= 0; i
< argc
; i
++) {
1107 struct commit
*commit
;
1109 o
= peel_to_type(argv
[i
], 0, NULL
, OBJ_COMMIT
);
1111 die(_("%s - not something we can merge"), argv
[i
]);
1112 commit
= lookup_commit(o
->sha1
);
1113 commit
->util
= (void *)argv
[i
];
1114 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1116 strbuf_addf(&buf
, "GITHEAD_%s", sha1_to_hex(o
->sha1
));
1117 setenv(buf
.buf
, argv
[i
], 1);
1121 if (!use_strategies
) {
1122 if (!remoteheads
->next
)
1123 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
1125 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
1128 for (i
= 0; i
< use_strategies_nr
; i
++) {
1129 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
1130 allow_fast_forward
= 0;
1131 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
1135 if (!remoteheads
->next
)
1136 common
= get_merge_bases(lookup_commit(head
),
1137 remoteheads
->item
, 1);
1139 struct commit_list
*list
= remoteheads
;
1140 commit_list_insert(lookup_commit(head
), &list
);
1141 common
= get_octopus_merge_bases(list
);
1145 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head
, NULL
, 0,
1149 ; /* No common ancestors found. We need a real merge. */
1150 else if (!remoteheads
->next
&& !common
->next
&&
1151 common
->item
== remoteheads
->item
) {
1153 * If head can reach all the merge then we are up to date.
1154 * but first the most common case of merging one remote.
1156 finish_up_to_date("Already up-to-date.");
1158 } else if (allow_fast_forward
&& !remoteheads
->next
&&
1160 !hashcmp(common
->item
->object
.sha1
, head
)) {
1161 /* Again the most common case of merging one remote. */
1162 struct strbuf msg
= STRBUF_INIT
;
1166 strcpy(hex
, find_unique_abbrev(head
, DEFAULT_ABBREV
));
1169 printf(_("Updating %s..%s\n"),
1171 find_unique_abbrev(remoteheads
->item
->object
.sha1
,
1173 strbuf_addstr(&msg
, "Fast-forward");
1176 " (no commit created; -m option ignored)");
1177 o
= peel_to_type(sha1_to_hex(remoteheads
->item
->object
.sha1
),
1178 0, NULL
, OBJ_COMMIT
);
1182 if (checkout_fast_forward(head
, remoteheads
->item
->object
.sha1
))
1185 finish(o
->sha1
, msg
.buf
);
1188 } else if (!remoteheads
->next
&& common
->next
)
1191 * We are not doing octopus and not fast-forward. Need
1194 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1196 * We are not doing octopus, not fast-forward, and have
1199 refresh_cache(REFRESH_QUIET
);
1200 if (allow_trivial
&& !fast_forward_only
) {
1201 /* See if it is really trivial. */
1202 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1203 printf(_("Trying really trivial in-index merge...\n"));
1204 if (!read_tree_trivial(common
->item
->object
.sha1
,
1205 head
, remoteheads
->item
->object
.sha1
))
1206 return merge_trivial();
1207 printf(_("Nope.\n"));
1211 * An octopus. If we can reach all the remote we are up
1215 struct commit_list
*j
;
1217 for (j
= remoteheads
; j
; j
= j
->next
) {
1218 struct commit_list
*common_one
;
1221 * Here we *have* to calculate the individual
1222 * merge_bases again, otherwise "git merge HEAD^
1223 * HEAD^^" would be missed.
1225 common_one
= get_merge_bases(lookup_commit(head
),
1227 if (hashcmp(common_one
->item
->object
.sha1
,
1228 j
->item
->object
.sha1
)) {
1234 finish_up_to_date("Already up-to-date. Yeeah!");
1239 if (fast_forward_only
)
1240 die(_("Not possible to fast-forward, aborting."));
1242 /* We are going to make a new commit. */
1243 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1246 * At this point, we need a real merge. No matter what strategy
1247 * we use, it would operate on the index, possibly affecting the
1248 * working tree, and when resolved cleanly, have the desired
1249 * tree in the index -- this means that the index must be in
1250 * sync with the head commit. The strategies are responsible
1253 if (use_strategies_nr
!= 1) {
1255 * Stash away the local changes so that we can try more
1260 memcpy(stash
, null_sha1
, 20);
1263 for (i
= 0; i
< use_strategies_nr
; i
++) {
1266 printf(_("Rewinding the tree to pristine...\n"));
1269 if (use_strategies_nr
!= 1)
1270 printf(_("Trying merge strategy %s...\n"),
1271 use_strategies
[i
]->name
);
1273 * Remember which strategy left the state in the working
1276 wt_strategy
= use_strategies
[i
]->name
;
1278 ret
= try_merge_strategy(use_strategies
[i
]->name
,
1280 if (!option_commit
&& !ret
) {
1283 * This is necessary here just to avoid writing
1284 * the tree, but later we will *not* exit with
1285 * status code 1 because merge_was_ok is set.
1292 * The backend exits with 1 when conflicts are
1293 * left to be resolved, with 2 when it does not
1294 * handle the given merge at all.
1297 int cnt
= evaluate_result();
1299 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1300 best_strategy
= use_strategies
[i
]->name
;
1310 /* Automerge succeeded. */
1311 write_tree_trivial(result_tree
);
1312 automerge_was_ok
= 1;
1317 * If we have a resulting tree, that means the strategy module
1318 * auto resolved the merge cleanly.
1320 if (automerge_was_ok
)
1321 return finish_automerge(common
, result_tree
, wt_strategy
);
1324 * Pick the result from the best strategy and have the user fix
1327 if (!best_strategy
) {
1329 if (use_strategies_nr
> 1)
1331 _("No merge strategy handled the merge.\n"));
1333 fprintf(stderr
, _("Merge with strategy %s failed.\n"),
1334 use_strategies
[0]->name
);
1336 } else if (best_strategy
== wt_strategy
)
1337 ; /* We already have its result in the working tree. */
1339 printf(_("Rewinding the tree to pristine...\n"));
1341 printf(_("Using the %s to prepare resolving by hand.\n"),
1343 try_merge_strategy(best_strategy
, common
, head_arg
);
1350 struct commit_list
*j
;
1352 for (j
= remoteheads
; j
; j
= j
->next
)
1353 strbuf_addf(&buf
, "%s\n",
1354 sha1_to_hex(j
->item
->object
.sha1
));
1355 fd
= open(git_path("MERGE_HEAD"), O_WRONLY
| O_CREAT
, 0666);
1357 die_errno(_("Could not open '%s' for writing"),
1358 git_path("MERGE_HEAD"));
1359 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1360 die_errno(_("Could not write to '%s'"), git_path("MERGE_HEAD"));
1362 strbuf_addch(&merge_msg
, '\n');
1364 fd
= open(git_path("MERGE_MODE"), O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
1366 die_errno(_("Could not open '%s' for writing"),
1367 git_path("MERGE_MODE"));
1369 if (!allow_fast_forward
)
1370 strbuf_addf(&buf
, "no-ff");
1371 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1372 die_errno(_("Could not write to '%s'"), git_path("MERGE_MODE"));
1377 fprintf(stderr
, _("Automatic merge went well; "
1378 "stopped before committing as requested\n"));
1381 return suggest_conflicts(option_renormalize
);