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 "message to be used for the merge commit (if any)",
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)
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
, struct commit_list
*common
,
588 const char *head_arg
, struct commit_list
*remotes
)
591 int i
= 0, x
= 0, ret
;
592 struct commit_list
*j
;
593 struct strbuf buf
= STRBUF_INIT
;
595 args
= xmalloc((4 + xopts_nr
+ commit_list_count(common
) +
596 commit_list_count(remotes
)) * sizeof(char *));
597 strbuf_addf(&buf
, "merge-%s", strategy
);
599 for (x
= 0; x
< xopts_nr
; x
++) {
600 char *s
= xmalloc(strlen(xopts
[x
])+2+1);
602 strcpy(s
+2, xopts
[x
]);
605 for (j
= common
; j
; j
= j
->next
)
606 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
608 args
[i
++] = head_arg
;
609 for (j
= remotes
; j
; j
= j
->next
)
610 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
612 ret
= run_command_v_opt(args
, RUN_GIT_CMD
);
613 strbuf_release(&buf
);
615 for (x
= 0; x
< xopts_nr
; x
++)
616 free((void *)args
[i
++]);
617 for (j
= common
; j
; j
= j
->next
)
618 free((void *)args
[i
++]);
620 for (j
= remotes
; j
; j
= j
->next
)
621 free((void *)args
[i
++]);
624 if (read_cache() < 0)
625 die("failed to read the cache");
626 resolve_undo_clear();
631 static int try_merge_strategy(const char *strategy
, struct commit_list
*common
,
632 const char *head_arg
)
635 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
637 index_fd
= hold_locked_index(lock
, 1);
638 refresh_cache(REFRESH_QUIET
);
639 if (active_cache_changed
&&
640 (write_cache(index_fd
, active_cache
, active_nr
) ||
641 commit_locked_index(lock
)))
642 return error("Unable to write index.");
643 rollback_lock_file(lock
);
645 if (!strcmp(strategy
, "recursive") || !strcmp(strategy
, "subtree")) {
647 struct commit
*result
;
648 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
650 struct commit_list
*reversed
= NULL
;
651 struct merge_options o
;
652 struct commit_list
*j
;
654 if (remoteheads
->next
) {
655 error("Not handling anything other than two heads merge.");
659 init_merge_options(&o
);
660 if (!strcmp(strategy
, "subtree"))
661 o
.subtree_shift
= "";
663 o
.renormalize
= option_renormalize
;
664 o
.show_rename_progress
=
665 show_progress
== -1 ? isatty(2) : show_progress
;
667 for (x
= 0; x
< xopts_nr
; x
++)
668 if (parse_merge_opt(&o
, xopts
[x
]))
669 die("Unknown option for merge-recursive: -X%s", xopts
[x
]);
671 o
.branch1
= head_arg
;
672 o
.branch2
= remoteheads
->item
->util
;
674 for (j
= common
; j
; j
= j
->next
)
675 commit_list_insert(j
->item
, &reversed
);
677 index_fd
= hold_locked_index(lock
, 1);
678 clean
= merge_recursive(&o
, lookup_commit(head
),
679 remoteheads
->item
, reversed
, &result
);
680 if (active_cache_changed
&&
681 (write_cache(index_fd
, active_cache
, active_nr
) ||
682 commit_locked_index(lock
)))
683 die ("unable to write %s", get_index_file());
684 rollback_lock_file(lock
);
685 return clean
? 0 : 1;
687 return try_merge_command(strategy
, common
, head_arg
, remoteheads
);
691 static void count_diff_files(struct diff_queue_struct
*q
,
692 struct diff_options
*opt
, void *data
)
699 static int count_unmerged_entries(void)
703 for (i
= 0; i
< active_nr
; i
++)
704 if (ce_stage(active_cache
[i
]))
710 int checkout_fast_forward(const unsigned char *head
, const unsigned char *remote
)
712 struct tree
*trees
[MAX_UNPACK_TREES
];
713 struct unpack_trees_options opts
;
714 struct tree_desc t
[MAX_UNPACK_TREES
];
715 int i
, fd
, nr_trees
= 0;
716 struct dir_struct dir
;
717 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
719 refresh_cache(REFRESH_QUIET
);
721 fd
= hold_locked_index(lock_file
, 1);
723 memset(&trees
, 0, sizeof(trees
));
724 memset(&opts
, 0, sizeof(opts
));
725 memset(&t
, 0, sizeof(t
));
726 memset(&dir
, 0, sizeof(dir
));
727 dir
.flags
|= DIR_SHOW_IGNORED
;
728 dir
.exclude_per_dir
= ".gitignore";
732 opts
.src_index
= &the_index
;
733 opts
.dst_index
= &the_index
;
735 opts
.verbose_update
= 1;
737 opts
.fn
= twoway_merge
;
738 setup_unpack_trees_porcelain(&opts
, "merge");
740 trees
[nr_trees
] = parse_tree_indirect(head
);
741 if (!trees
[nr_trees
++])
743 trees
[nr_trees
] = parse_tree_indirect(remote
);
744 if (!trees
[nr_trees
++])
746 for (i
= 0; i
< nr_trees
; i
++) {
747 parse_tree(trees
[i
]);
748 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
750 if (unpack_trees(nr_trees
, t
, &opts
))
752 if (write_cache(fd
, active_cache
, active_nr
) ||
753 commit_locked_index(lock_file
))
754 die("unable to write new index file");
758 static void split_merge_strategies(const char *string
, struct strategy
**list
,
766 buf
= xstrdup(string
);
771 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
772 (*list
)[(*nr
)++].name
= xstrdup(q
);
777 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
778 (*list
)[(*nr
)++].name
= xstrdup(q
);
784 static void add_strategies(const char *string
, unsigned attr
)
786 struct strategy
*list
= NULL
;
787 int list_alloc
= 0, list_nr
= 0, i
;
789 memset(&list
, 0, sizeof(list
));
790 split_merge_strategies(string
, &list
, &list_nr
, &list_alloc
);
792 for (i
= 0; i
< list_nr
; i
++)
793 append_strategy(get_strategy(list
[i
].name
));
796 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
797 if (all_strategy
[i
].attr
& attr
)
798 append_strategy(&all_strategy
[i
]);
802 static int merge_trivial(void)
804 unsigned char result_tree
[20], result_commit
[20];
805 struct commit_list
*parent
= xmalloc(sizeof(*parent
));
807 write_tree_trivial(result_tree
);
808 printf("Wonderful.\n");
809 parent
->item
= lookup_commit(head
);
810 parent
->next
= xmalloc(sizeof(*parent
->next
));
811 parent
->next
->item
= remoteheads
->item
;
812 parent
->next
->next
= NULL
;
813 commit_tree(merge_msg
.buf
, result_tree
, parent
, result_commit
, NULL
);
814 finish(result_commit
, "In-index merge");
819 static int finish_automerge(struct commit_list
*common
,
820 unsigned char *result_tree
,
821 const char *wt_strategy
)
823 struct commit_list
*parents
= NULL
, *j
;
824 struct strbuf buf
= STRBUF_INIT
;
825 unsigned char result_commit
[20];
827 free_commit_list(common
);
828 if (allow_fast_forward
) {
829 parents
= remoteheads
;
830 commit_list_insert(lookup_commit(head
), &parents
);
831 parents
= reduce_heads(parents
);
833 struct commit_list
**pptr
= &parents
;
835 pptr
= &commit_list_insert(lookup_commit(head
),
837 for (j
= remoteheads
; j
; j
= j
->next
)
838 pptr
= &commit_list_insert(j
->item
, pptr
)->next
;
840 free_commit_list(remoteheads
);
841 strbuf_addch(&merge_msg
, '\n');
842 commit_tree(merge_msg
.buf
, result_tree
, parents
, result_commit
, NULL
);
843 strbuf_addf(&buf
, "Merge made by %s.", wt_strategy
);
844 finish(result_commit
, buf
.buf
);
845 strbuf_release(&buf
);
850 static int suggest_conflicts(int renormalizing
)
855 fp
= fopen(git_path("MERGE_MSG"), "a");
857 die_errno("Could not open '%s' for writing",
858 git_path("MERGE_MSG"));
859 fprintf(fp
, "\nConflicts:\n");
860 for (pos
= 0; pos
< active_nr
; pos
++) {
861 struct cache_entry
*ce
= active_cache
[pos
];
864 fprintf(fp
, "\t%s\n", ce
->name
);
865 while (pos
+ 1 < active_nr
&&
867 active_cache
[pos
+ 1]->name
))
872 rerere(allow_rerere_auto
);
873 printf("Automatic merge failed; "
874 "fix conflicts and then commit the result.\n");
878 static struct commit
*is_old_style_invocation(int argc
, const char **argv
)
880 struct commit
*second_token
= NULL
;
882 unsigned char second_sha1
[20];
884 if (get_sha1(argv
[1], second_sha1
))
886 second_token
= lookup_commit_reference_gently(second_sha1
, 0);
888 die("'%s' is not a commit", argv
[1]);
889 if (hashcmp(second_token
->object
.sha1
, head
))
895 static int evaluate_result(void)
900 /* Check how many files differ. */
901 init_revisions(&rev
, "");
902 setup_revisions(0, NULL
, &rev
, NULL
);
903 rev
.diffopt
.output_format
|=
904 DIFF_FORMAT_CALLBACK
;
905 rev
.diffopt
.format_callback
= count_diff_files
;
906 rev
.diffopt
.format_callback_data
= &cnt
;
907 run_diff_files(&rev
, 0);
910 * Check how many unmerged entries are
913 cnt
+= count_unmerged_entries();
918 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
920 unsigned char result_tree
[20];
921 struct strbuf buf
= STRBUF_INIT
;
922 const char *head_arg
;
923 int flag
, head_invalid
= 0, i
;
924 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
925 struct commit_list
*common
= NULL
;
926 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
927 struct commit_list
**remotes
= &remoteheads
;
929 if (argc
== 2 && !strcmp(argv
[1], "-h"))
930 usage_with_options(builtin_merge_usage
, builtin_merge_options
);
933 * Check if we are _not_ on a detached HEAD, i.e. if there is a
936 branch
= resolve_ref("HEAD", head
, 0, &flag
);
937 if (branch
&& !prefixcmp(branch
, "refs/heads/"))
939 if (is_null_sha1(head
))
942 git_config(git_merge_config
, NULL
);
945 if (diff_use_color_default
== -1)
946 diff_use_color_default
= git_use_color_default
;
948 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
949 builtin_merge_usage
, 0);
951 if (verbosity
< 0 && show_progress
== -1)
954 if (abort_current_merge
) {
956 const char *nargv
[] = {"reset", "--merge", NULL
};
958 if (!file_exists(git_path("MERGE_HEAD")))
959 die("There is no merge to abort (MERGE_HEAD missing).");
961 /* Invoke 'git reset --merge' */
962 return cmd_reset(nargc
, nargv
, prefix
);
965 if (read_cache_unmerged())
966 die_resolve_conflict("merge");
968 if (file_exists(git_path("MERGE_HEAD"))) {
970 * There is no unmerged entry, don't advise 'git
971 * add/rm <file>', just 'git commit'.
973 if (advice_resolve_conflict
)
974 die("You have not concluded your merge (MERGE_HEAD exists).\n"
975 "Please, commit your changes before you can merge.");
977 die("You have not concluded your merge (MERGE_HEAD exists).");
979 resolve_undo_clear();
985 if (!allow_fast_forward
)
986 die("You cannot combine --squash with --no-ff.");
990 if (!allow_fast_forward
&& fast_forward_only
)
991 die("You cannot combine --no-ff with --ff-only.");
994 usage_with_options(builtin_merge_usage
,
995 builtin_merge_options
);
998 * This could be traditional "merge <msg> HEAD <commit>..." and
999 * the way we can tell it is to see if the second token is HEAD,
1000 * but some people might have misused the interface and used a
1001 * committish that is the same as HEAD there instead.
1002 * Traditional format never would have "-m" so it is an
1003 * additional safety measure to check for it.
1006 if (!have_message
&& is_old_style_invocation(argc
, argv
)) {
1007 strbuf_addstr(&merge_msg
, argv
[0]);
1011 } else if (head_invalid
) {
1012 struct object
*remote_head
;
1014 * If the merged head is a valid one there is no reason
1015 * to forbid "git merge" into a branch yet to be born.
1016 * We do the same for "git pull".
1019 die("Can merge only exactly one commit into "
1022 die("Squash commit into empty head not supported yet");
1023 if (!allow_fast_forward
)
1024 die("Non-fast-forward commit does not make sense into "
1026 remote_head
= peel_to_type(argv
[0], 0, NULL
, OBJ_COMMIT
);
1028 die("%s - not something we can merge", argv
[0]);
1029 update_ref("initial pull", "HEAD", remote_head
->sha1
, NULL
, 0,
1031 read_empty(remote_head
->sha1
, 0);
1034 struct strbuf merge_names
= STRBUF_INIT
;
1036 /* We are invoked directly as the first-class UI. */
1040 * All the rest are the commits being merged;
1041 * prepare the standard merge summary message to
1042 * be appended to the given message. If remote
1043 * is invalid we will die later in the common
1044 * codepath so we discard the error in this
1047 for (i
= 0; i
< argc
; i
++)
1048 merge_name(argv
[i
], &merge_names
);
1050 if (!have_message
|| shortlog_len
) {
1051 fmt_merge_msg(&merge_names
, &merge_msg
, !have_message
,
1054 strbuf_setlen(&merge_msg
, merge_msg
.len
- 1);
1058 if (head_invalid
|| !argc
)
1059 usage_with_options(builtin_merge_usage
,
1060 builtin_merge_options
);
1062 strbuf_addstr(&buf
, "merge");
1063 for (i
= 0; i
< argc
; i
++)
1064 strbuf_addf(&buf
, " %s", argv
[i
]);
1065 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
1068 for (i
= 0; i
< argc
; i
++) {
1070 struct commit
*commit
;
1072 o
= peel_to_type(argv
[i
], 0, NULL
, OBJ_COMMIT
);
1074 die("%s - not something we can merge", argv
[i
]);
1075 commit
= lookup_commit(o
->sha1
);
1076 commit
->util
= (void *)argv
[i
];
1077 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1079 strbuf_addf(&buf
, "GITHEAD_%s", sha1_to_hex(o
->sha1
));
1080 setenv(buf
.buf
, argv
[i
], 1);
1084 if (!use_strategies
) {
1085 if (!remoteheads
->next
)
1086 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
1088 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
1091 for (i
= 0; i
< use_strategies_nr
; i
++) {
1092 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
1093 allow_fast_forward
= 0;
1094 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
1098 if (!remoteheads
->next
)
1099 common
= get_merge_bases(lookup_commit(head
),
1100 remoteheads
->item
, 1);
1102 struct commit_list
*list
= remoteheads
;
1103 commit_list_insert(lookup_commit(head
), &list
);
1104 common
= get_octopus_merge_bases(list
);
1108 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head
, NULL
, 0,
1112 ; /* No common ancestors found. We need a real merge. */
1113 else if (!remoteheads
->next
&& !common
->next
&&
1114 common
->item
== remoteheads
->item
) {
1116 * If head can reach all the merge then we are up to date.
1117 * but first the most common case of merging one remote.
1119 finish_up_to_date("Already up-to-date.");
1121 } else if (allow_fast_forward
&& !remoteheads
->next
&&
1123 !hashcmp(common
->item
->object
.sha1
, head
)) {
1124 /* Again the most common case of merging one remote. */
1125 struct strbuf msg
= STRBUF_INIT
;
1129 strcpy(hex
, find_unique_abbrev(head
, DEFAULT_ABBREV
));
1132 printf("Updating %s..%s\n",
1134 find_unique_abbrev(remoteheads
->item
->object
.sha1
,
1136 strbuf_addstr(&msg
, "Fast-forward");
1139 " (no commit created; -m option ignored)");
1140 o
= peel_to_type(sha1_to_hex(remoteheads
->item
->object
.sha1
),
1141 0, NULL
, OBJ_COMMIT
);
1145 if (checkout_fast_forward(head
, remoteheads
->item
->object
.sha1
))
1148 finish(o
->sha1
, msg
.buf
);
1151 } else if (!remoteheads
->next
&& common
->next
)
1154 * We are not doing octopus and not fast-forward. Need
1157 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1159 * We are not doing octopus, not fast-forward, and have
1162 refresh_cache(REFRESH_QUIET
);
1163 if (allow_trivial
&& !fast_forward_only
) {
1164 /* See if it is really trivial. */
1165 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1166 printf("Trying really trivial in-index merge...\n");
1167 if (!read_tree_trivial(common
->item
->object
.sha1
,
1168 head
, remoteheads
->item
->object
.sha1
))
1169 return merge_trivial();
1174 * An octopus. If we can reach all the remote we are up
1178 struct commit_list
*j
;
1180 for (j
= remoteheads
; j
; j
= j
->next
) {
1181 struct commit_list
*common_one
;
1184 * Here we *have* to calculate the individual
1185 * merge_bases again, otherwise "git merge HEAD^
1186 * HEAD^^" would be missed.
1188 common_one
= get_merge_bases(lookup_commit(head
),
1190 if (hashcmp(common_one
->item
->object
.sha1
,
1191 j
->item
->object
.sha1
)) {
1197 finish_up_to_date("Already up-to-date. Yeeah!");
1202 if (fast_forward_only
)
1203 die("Not possible to fast-forward, aborting.");
1205 /* We are going to make a new commit. */
1206 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1209 * At this point, we need a real merge. No matter what strategy
1210 * we use, it would operate on the index, possibly affecting the
1211 * working tree, and when resolved cleanly, have the desired
1212 * tree in the index -- this means that the index must be in
1213 * sync with the head commit. The strategies are responsible
1216 if (use_strategies_nr
!= 1) {
1218 * Stash away the local changes so that we can try more
1223 memcpy(stash
, null_sha1
, 20);
1226 for (i
= 0; i
< use_strategies_nr
; i
++) {
1229 printf("Rewinding the tree to pristine...\n");
1232 if (use_strategies_nr
!= 1)
1233 printf("Trying merge strategy %s...\n",
1234 use_strategies
[i
]->name
);
1236 * Remember which strategy left the state in the working
1239 wt_strategy
= use_strategies
[i
]->name
;
1241 ret
= try_merge_strategy(use_strategies
[i
]->name
,
1243 if (!option_commit
&& !ret
) {
1246 * This is necessary here just to avoid writing
1247 * the tree, but later we will *not* exit with
1248 * status code 1 because merge_was_ok is set.
1255 * The backend exits with 1 when conflicts are
1256 * left to be resolved, with 2 when it does not
1257 * handle the given merge at all.
1260 int cnt
= evaluate_result();
1262 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1263 best_strategy
= use_strategies
[i
]->name
;
1273 /* Automerge succeeded. */
1274 write_tree_trivial(result_tree
);
1275 automerge_was_ok
= 1;
1280 * If we have a resulting tree, that means the strategy module
1281 * auto resolved the merge cleanly.
1283 if (automerge_was_ok
)
1284 return finish_automerge(common
, result_tree
, wt_strategy
);
1287 * Pick the result from the best strategy and have the user fix
1290 if (!best_strategy
) {
1292 if (use_strategies_nr
> 1)
1294 "No merge strategy handled the merge.\n");
1296 fprintf(stderr
, "Merge with strategy %s failed.\n",
1297 use_strategies
[0]->name
);
1299 } else if (best_strategy
== wt_strategy
)
1300 ; /* We already have its result in the working tree. */
1302 printf("Rewinding the tree to pristine...\n");
1304 printf("Using the %s to prepare resolving by hand.\n",
1306 try_merge_strategy(best_strategy
, common
, head_arg
);
1313 struct commit_list
*j
;
1315 for (j
= remoteheads
; j
; j
= j
->next
)
1316 strbuf_addf(&buf
, "%s\n",
1317 sha1_to_hex(j
->item
->object
.sha1
));
1318 fd
= open(git_path("MERGE_HEAD"), O_WRONLY
| O_CREAT
, 0666);
1320 die_errno("Could not open '%s' for writing",
1321 git_path("MERGE_HEAD"));
1322 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1323 die_errno("Could not write to '%s'", git_path("MERGE_HEAD"));
1325 strbuf_addch(&merge_msg
, '\n');
1326 fd
= open(git_path("MERGE_MSG"), O_WRONLY
| O_CREAT
, 0666);
1328 die_errno("Could not open '%s' for writing",
1329 git_path("MERGE_MSG"));
1330 if (write_in_full(fd
, merge_msg
.buf
, merge_msg
.len
) !=
1332 die_errno("Could not write to '%s'", git_path("MERGE_MSG"));
1334 fd
= open(git_path("MERGE_MODE"), O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
1336 die_errno("Could not open '%s' for writing",
1337 git_path("MERGE_MODE"));
1339 if (!allow_fast_forward
)
1340 strbuf_addf(&buf
, "no-ff");
1341 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1342 die_errno("Could not write to '%s'", git_path("MERGE_MODE"));
1347 fprintf(stderr
, "Automatic merge went well; "
1348 "stopped before committing as requested\n");
1351 return suggest_conflicts(option_renormalize
);