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"
30 #define DEFAULT_TWOHEAD (1<<0)
31 #define DEFAULT_OCTOPUS (1<<1)
32 #define NO_FAST_FORWARD (1<<2)
33 #define NO_TRIVIAL (1<<3)
40 static const char * const builtin_merge_usage
[] = {
41 "git merge [options] [<commit>...]",
42 "git merge [options] <msg> HEAD <commit>",
47 static int show_diffstat
= 1, shortlog_len
, squash
;
48 static int option_commit
= 1, allow_fast_forward
= 1;
49 static int fast_forward_only
;
50 static int allow_trivial
= 1, have_message
;
51 static struct strbuf merge_msg
;
52 static struct commit_list
*remoteheads
;
53 static unsigned char head
[20], stash
[20];
54 static struct strategy
**use_strategies
;
55 static size_t use_strategies_nr
, use_strategies_alloc
;
56 static const char **xopts
;
57 static size_t xopts_nr
, xopts_alloc
;
58 static const char *branch
;
59 static int option_renormalize
;
61 static int allow_rerere_auto
;
62 static int abort_current_merge
;
63 static int default_to_upstream
;
65 static struct strategy all_strategy
[] = {
66 { "recursive", DEFAULT_TWOHEAD
| NO_TRIVIAL
},
67 { "octopus", DEFAULT_OCTOPUS
},
69 { "ours", NO_FAST_FORWARD
| NO_TRIVIAL
},
70 { "subtree", NO_FAST_FORWARD
| NO_TRIVIAL
},
73 static const char *pull_twohead
, *pull_octopus
;
75 static int option_parse_message(const struct option
*opt
,
76 const char *arg
, int unset
)
78 struct strbuf
*buf
= opt
->value
;
81 strbuf_setlen(buf
, 0);
83 strbuf_addf(buf
, "%s%s", buf
->len
? "\n\n" : "", arg
);
86 return error("switch `m' requires a value");
90 static struct strategy
*get_strategy(const char *name
)
94 static struct cmdnames main_cmds
, other_cmds
;
100 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
101 if (!strcmp(name
, all_strategy
[i
].name
))
102 return &all_strategy
[i
];
105 struct cmdnames not_strategies
;
108 memset(¬_strategies
, 0, sizeof(struct cmdnames
));
109 load_command_list("git-merge-", &main_cmds
, &other_cmds
);
110 for (i
= 0; i
< main_cmds
.cnt
; i
++) {
112 struct cmdname
*ent
= main_cmds
.names
[i
];
113 for (j
= 0; j
< ARRAY_SIZE(all_strategy
); j
++)
114 if (!strncmp(ent
->name
, all_strategy
[j
].name
, ent
->len
)
115 && !all_strategy
[j
].name
[ent
->len
])
118 add_cmdname(¬_strategies
, ent
->name
, ent
->len
);
120 exclude_cmds(&main_cmds
, ¬_strategies
);
122 if (!is_in_cmdlist(&main_cmds
, name
) && !is_in_cmdlist(&other_cmds
, name
)) {
123 fprintf(stderr
, "Could not find merge strategy '%s'.\n", name
);
124 fprintf(stderr
, "Available strategies are:");
125 for (i
= 0; i
< main_cmds
.cnt
; i
++)
126 fprintf(stderr
, " %s", main_cmds
.names
[i
]->name
);
127 fprintf(stderr
, ".\n");
128 if (other_cmds
.cnt
) {
129 fprintf(stderr
, "Available custom strategies are:");
130 for (i
= 0; i
< other_cmds
.cnt
; i
++)
131 fprintf(stderr
, " %s", other_cmds
.names
[i
]->name
);
132 fprintf(stderr
, ".\n");
137 ret
= xcalloc(1, sizeof(struct strategy
));
138 ret
->name
= xstrdup(name
);
139 ret
->attr
= NO_TRIVIAL
;
143 static void append_strategy(struct strategy
*s
)
145 ALLOC_GROW(use_strategies
, use_strategies_nr
+ 1, use_strategies_alloc
);
146 use_strategies
[use_strategies_nr
++] = s
;
149 static int option_parse_strategy(const struct option
*opt
,
150 const char *name
, int unset
)
155 append_strategy(get_strategy(name
));
159 static int option_parse_x(const struct option
*opt
,
160 const char *arg
, int unset
)
165 ALLOC_GROW(xopts
, xopts_nr
+ 1, xopts_alloc
);
166 xopts
[xopts_nr
++] = xstrdup(arg
);
170 static int option_parse_n(const struct option
*opt
,
171 const char *arg
, int unset
)
173 show_diffstat
= unset
;
177 static struct option builtin_merge_options
[] = {
178 { OPTION_CALLBACK
, 'n', NULL
, NULL
, NULL
,
179 "do not show a diffstat at the end of the merge",
180 PARSE_OPT_NOARG
, option_parse_n
},
181 OPT_BOOLEAN(0, "stat", &show_diffstat
,
182 "show a diffstat at the end of the merge"),
183 OPT_BOOLEAN(0, "summary", &show_diffstat
, "(synonym to --stat)"),
184 { OPTION_INTEGER
, 0, "log", &shortlog_len
, "n",
185 "add (at most <n>) entries from shortlog to merge commit message",
186 PARSE_OPT_OPTARG
, NULL
, DEFAULT_MERGE_LOG_LEN
},
187 OPT_BOOLEAN(0, "squash", &squash
,
188 "create a single commit instead of doing a merge"),
189 OPT_BOOLEAN(0, "commit", &option_commit
,
190 "perform a commit if the merge succeeds (default)"),
191 OPT_BOOLEAN(0, "ff", &allow_fast_forward
,
192 "allow fast-forward (default)"),
193 OPT_BOOLEAN(0, "ff-only", &fast_forward_only
,
194 "abort if fast-forward is not possible"),
195 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto
),
196 OPT_CALLBACK('s', "strategy", &use_strategies
, "strategy",
197 "merge strategy to use", option_parse_strategy
),
198 OPT_CALLBACK('X', "strategy-option", &xopts
, "option=value",
199 "option for selected merge strategy", option_parse_x
),
200 OPT_CALLBACK('m', "message", &merge_msg
, "message",
201 "message to be used for the merge commit (if any)",
202 option_parse_message
),
203 OPT__VERBOSITY(&verbosity
),
204 OPT_BOOLEAN(0, "abort", &abort_current_merge
,
205 "abort the current in-progress merge"),
209 /* Cleans up metadata that is uninteresting after a succeeded merge. */
210 static void drop_save(void)
212 unlink(git_path("MERGE_HEAD"));
213 unlink(git_path("MERGE_MSG"));
214 unlink(git_path("MERGE_MODE"));
217 static void save_state(void)
220 struct child_process cp
;
221 struct strbuf buffer
= STRBUF_INIT
;
222 const char *argv
[] = {"stash", "create", NULL
};
224 memset(&cp
, 0, sizeof(cp
));
229 if (start_command(&cp
))
230 die("could not run stash.");
231 len
= strbuf_read(&buffer
, cp
.out
, 1024);
234 if (finish_command(&cp
) || len
< 0)
238 strbuf_setlen(&buffer
, buffer
.len
-1);
239 if (get_sha1(buffer
.buf
, stash
))
240 die("not a valid object: %s", buffer
.buf
);
243 static void read_empty(unsigned const char *sha1
, int verbose
)
248 args
[i
++] = "read-tree";
253 args
[i
++] = EMPTY_TREE_SHA1_HEX
;
254 args
[i
++] = sha1_to_hex(sha1
);
257 if (run_command_v_opt(args
, RUN_GIT_CMD
))
258 die("read-tree failed");
261 static void reset_hard(unsigned const char *sha1
, int verbose
)
266 args
[i
++] = "read-tree";
269 args
[i
++] = "--reset";
271 args
[i
++] = sha1_to_hex(sha1
);
274 if (run_command_v_opt(args
, RUN_GIT_CMD
))
275 die("read-tree failed");
278 static void restore_state(void)
280 struct strbuf sb
= STRBUF_INIT
;
281 const char *args
[] = { "stash", "apply", NULL
, NULL
};
283 if (is_null_sha1(stash
))
288 args
[2] = sha1_to_hex(stash
);
291 * It is OK to ignore error here, for example when there was
292 * nothing to restore.
294 run_command_v_opt(args
, RUN_GIT_CMD
);
297 refresh_cache(REFRESH_QUIET
);
300 /* This is called when no merge was necessary. */
301 static void finish_up_to_date(const char *msg
)
304 printf("%s%s\n", squash
? " (nothing to squash)" : "", msg
);
308 static void squash_message(void)
311 struct commit
*commit
;
312 struct strbuf out
= STRBUF_INIT
;
313 struct commit_list
*j
;
315 struct pretty_print_context ctx
= {0};
317 printf("Squash commit -- not updating HEAD\n");
318 fd
= open(git_path("SQUASH_MSG"), O_WRONLY
| O_CREAT
, 0666);
320 die_errno("Could not write to '%s'", git_path("SQUASH_MSG"));
322 init_revisions(&rev
, NULL
);
323 rev
.ignore_merges
= 1;
324 rev
.commit_format
= CMIT_FMT_MEDIUM
;
326 commit
= lookup_commit(head
);
327 commit
->object
.flags
|= UNINTERESTING
;
328 add_pending_object(&rev
, &commit
->object
, NULL
);
330 for (j
= remoteheads
; j
; j
= j
->next
)
331 add_pending_object(&rev
, &j
->item
->object
, NULL
);
333 setup_revisions(0, NULL
, &rev
, NULL
);
334 if (prepare_revision_walk(&rev
))
335 die("revision walk setup failed");
337 ctx
.abbrev
= rev
.abbrev
;
338 ctx
.date_mode
= rev
.date_mode
;
340 strbuf_addstr(&out
, "Squashed commit of the following:\n");
341 while ((commit
= get_revision(&rev
)) != NULL
) {
342 strbuf_addch(&out
, '\n');
343 strbuf_addf(&out
, "commit %s\n",
344 sha1_to_hex(commit
->object
.sha1
));
345 pretty_print_commit(rev
.commit_format
, commit
, &out
, &ctx
);
347 if (write(fd
, out
.buf
, out
.len
) < 0)
348 die_errno("Writing SQUASH_MSG");
350 die_errno("Finishing SQUASH_MSG");
351 strbuf_release(&out
);
354 static void finish(const unsigned char *new_head
, const char *msg
)
356 struct strbuf reflog_message
= STRBUF_INIT
;
359 strbuf_addstr(&reflog_message
, getenv("GIT_REFLOG_ACTION"));
363 strbuf_addf(&reflog_message
, "%s: %s",
364 getenv("GIT_REFLOG_ACTION"), msg
);
369 if (verbosity
>= 0 && !merge_msg
.len
)
370 printf("No merge message -- not updating HEAD\n");
372 const char *argv_gc_auto
[] = { "gc", "--auto", NULL
};
373 update_ref(reflog_message
.buf
, "HEAD",
377 * We ignore errors in 'gc --auto', since the
378 * user should see them.
380 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
383 if (new_head
&& show_diffstat
) {
384 struct diff_options opts
;
386 opts
.output_format
|=
387 DIFF_FORMAT_SUMMARY
| DIFF_FORMAT_DIFFSTAT
;
388 opts
.detect_rename
= DIFF_DETECT_RENAME
;
389 if (diff_use_color_default
> 0)
390 DIFF_OPT_SET(&opts
, COLOR_DIFF
);
391 if (diff_setup_done(&opts
) < 0)
392 die("diff_setup_done failed");
393 diff_tree_sha1(head
, new_head
, "", &opts
);
398 /* Run a post-merge hook */
399 run_hook(NULL
, "post-merge", squash
? "1" : "0", NULL
);
401 strbuf_release(&reflog_message
);
404 /* Get the name for the merge commit's message. */
405 static void merge_name(const char *remote
, struct strbuf
*msg
)
407 struct object
*remote_head
;
408 unsigned char branch_head
[20], buf_sha
[20];
409 struct strbuf buf
= STRBUF_INIT
;
410 struct strbuf bname
= STRBUF_INIT
;
415 strbuf_branchname(&bname
, remote
);
418 memset(branch_head
, 0, sizeof(branch_head
));
419 remote_head
= peel_to_type(remote
, 0, NULL
, OBJ_COMMIT
);
421 die("'%s' does not point to a commit", remote
);
423 if (dwim_ref(remote
, strlen(remote
), branch_head
, &found_ref
) > 0) {
424 if (!prefixcmp(found_ref
, "refs/heads/")) {
425 strbuf_addf(msg
, "%s\t\tbranch '%s' of .\n",
426 sha1_to_hex(branch_head
), remote
);
429 if (!prefixcmp(found_ref
, "refs/remotes/")) {
430 strbuf_addf(msg
, "%s\t\tremote-tracking branch '%s' of .\n",
431 sha1_to_hex(branch_head
), remote
);
436 /* See if remote matches <name>^^^.. or <name>~<number> */
437 for (len
= 0, ptr
= remote
+ strlen(remote
);
438 remote
< ptr
&& ptr
[-1] == '^';
445 ptr
= strrchr(remote
, '~');
447 int seen_nonzero
= 0;
450 while (*++ptr
&& isdigit(*ptr
)) {
451 seen_nonzero
|= (*ptr
!= '0');
455 len
= 0; /* not ...~<number> */
456 else if (seen_nonzero
)
459 early
= 1; /* "name~" is "name~1"! */
463 struct strbuf truname
= STRBUF_INIT
;
464 strbuf_addstr(&truname
, "refs/heads/");
465 strbuf_addstr(&truname
, remote
);
466 strbuf_setlen(&truname
, truname
.len
- len
);
467 if (resolve_ref(truname
.buf
, buf_sha
, 1, NULL
)) {
469 "%s\t\tbranch '%s'%s of .\n",
470 sha1_to_hex(remote_head
->sha1
),
472 (early
? " (early part)" : ""));
473 strbuf_release(&truname
);
478 if (!strcmp(remote
, "FETCH_HEAD") &&
479 !access(git_path("FETCH_HEAD"), R_OK
)) {
481 struct strbuf line
= STRBUF_INIT
;
484 fp
= fopen(git_path("FETCH_HEAD"), "r");
486 die_errno("could not open '%s' for reading",
487 git_path("FETCH_HEAD"));
488 strbuf_getline(&line
, fp
, '\n');
490 ptr
= strstr(line
.buf
, "\tnot-for-merge\t");
492 strbuf_remove(&line
, ptr
-line
.buf
+1, 13);
493 strbuf_addbuf(msg
, &line
);
494 strbuf_release(&line
);
497 strbuf_addf(msg
, "%s\t\tcommit '%s'\n",
498 sha1_to_hex(remote_head
->sha1
), remote
);
500 strbuf_release(&buf
);
501 strbuf_release(&bname
);
504 static int git_merge_config(const char *k
, const char *v
, void *cb
)
506 if (branch
&& !prefixcmp(k
, "branch.") &&
507 !prefixcmp(k
+ 7, branch
) &&
508 !strcmp(k
+ 7 + strlen(branch
), ".mergeoptions")) {
514 argc
= split_cmdline(buf
, &argv
);
516 die("Bad branch.%s.mergeoptions string: %s", branch
,
517 split_cmdline_strerror(argc
));
518 argv
= xrealloc(argv
, sizeof(*argv
) * (argc
+ 2));
519 memmove(argv
+ 1, argv
, sizeof(*argv
) * (argc
+ 1));
521 parse_options(argc
, argv
, NULL
, builtin_merge_options
,
522 builtin_merge_usage
, 0);
526 if (!strcmp(k
, "merge.diffstat") || !strcmp(k
, "merge.stat"))
527 show_diffstat
= git_config_bool(k
, v
);
528 else if (!strcmp(k
, "pull.twohead"))
529 return git_config_string(&pull_twohead
, k
, v
);
530 else if (!strcmp(k
, "pull.octopus"))
531 return git_config_string(&pull_octopus
, k
, v
);
532 else if (!strcmp(k
, "merge.renormalize"))
533 option_renormalize
= git_config_bool(k
, v
);
534 else if (!strcmp(k
, "merge.log") || !strcmp(k
, "merge.summary")) {
536 shortlog_len
= git_config_bool_or_int(k
, v
, &is_bool
);
537 if (!is_bool
&& shortlog_len
< 0)
538 return error("%s: negative length %s", k
, v
);
539 if (is_bool
&& shortlog_len
)
540 shortlog_len
= DEFAULT_MERGE_LOG_LEN
;
542 } else if (!strcmp(k
, "merge.defaulttoupstream")) {
543 default_to_upstream
= git_config_bool(k
, v
);
546 return git_diff_ui_config(k
, v
, cb
);
549 static int read_tree_trivial(unsigned char *common
, unsigned char *head
,
553 struct tree
*trees
[MAX_UNPACK_TREES
];
554 struct tree_desc t
[MAX_UNPACK_TREES
];
555 struct unpack_trees_options opts
;
557 memset(&opts
, 0, sizeof(opts
));
559 opts
.src_index
= &the_index
;
560 opts
.dst_index
= &the_index
;
562 opts
.verbose_update
= 1;
563 opts
.trivial_merges_only
= 1;
565 trees
[nr_trees
] = parse_tree_indirect(common
);
566 if (!trees
[nr_trees
++])
568 trees
[nr_trees
] = parse_tree_indirect(head
);
569 if (!trees
[nr_trees
++])
571 trees
[nr_trees
] = parse_tree_indirect(one
);
572 if (!trees
[nr_trees
++])
574 opts
.fn
= threeway_merge
;
575 cache_tree_free(&active_cache_tree
);
576 for (i
= 0; i
< nr_trees
; i
++) {
577 parse_tree(trees
[i
]);
578 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
580 if (unpack_trees(nr_trees
, t
, &opts
))
585 static void write_tree_trivial(unsigned char *sha1
)
587 if (write_cache_as_tree(sha1
, 0, NULL
))
588 die("git write-tree failed to write a tree");
591 int try_merge_command(const char *strategy
, struct commit_list
*common
,
592 const char *head_arg
, struct commit_list
*remotes
)
595 int i
= 0, x
= 0, ret
;
596 struct commit_list
*j
;
597 struct strbuf buf
= STRBUF_INIT
;
599 args
= xmalloc((4 + xopts_nr
+ commit_list_count(common
) +
600 commit_list_count(remotes
)) * sizeof(char *));
601 strbuf_addf(&buf
, "merge-%s", strategy
);
603 for (x
= 0; x
< xopts_nr
; x
++) {
604 char *s
= xmalloc(strlen(xopts
[x
])+2+1);
606 strcpy(s
+2, xopts
[x
]);
609 for (j
= common
; j
; j
= j
->next
)
610 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
612 args
[i
++] = head_arg
;
613 for (j
= remotes
; j
; j
= j
->next
)
614 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
616 ret
= run_command_v_opt(args
, RUN_GIT_CMD
);
617 strbuf_release(&buf
);
619 for (x
= 0; x
< xopts_nr
; x
++)
620 free((void *)args
[i
++]);
621 for (j
= common
; j
; j
= j
->next
)
622 free((void *)args
[i
++]);
624 for (j
= remotes
; j
; j
= j
->next
)
625 free((void *)args
[i
++]);
628 if (read_cache() < 0)
629 die("failed to read the cache");
630 resolve_undo_clear();
635 static int try_merge_strategy(const char *strategy
, struct commit_list
*common
,
636 const char *head_arg
)
639 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
641 index_fd
= hold_locked_index(lock
, 1);
642 refresh_cache(REFRESH_QUIET
);
643 if (active_cache_changed
&&
644 (write_cache(index_fd
, active_cache
, active_nr
) ||
645 commit_locked_index(lock
)))
646 return error("Unable to write index.");
647 rollback_lock_file(lock
);
649 if (!strcmp(strategy
, "recursive") || !strcmp(strategy
, "subtree")) {
651 struct commit
*result
;
652 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
654 struct commit_list
*reversed
= NULL
;
655 struct merge_options o
;
656 struct commit_list
*j
;
658 if (remoteheads
->next
) {
659 error("Not handling anything other than two heads merge.");
663 init_merge_options(&o
);
664 if (!strcmp(strategy
, "subtree"))
665 o
.subtree_shift
= "";
667 o
.renormalize
= option_renormalize
;
669 for (x
= 0; x
< xopts_nr
; x
++)
670 if (parse_merge_opt(&o
, xopts
[x
]))
671 die("Unknown option for merge-recursive: -X%s", xopts
[x
]);
673 o
.branch1
= head_arg
;
674 o
.branch2
= remoteheads
->item
->util
;
676 for (j
= common
; j
; j
= j
->next
)
677 commit_list_insert(j
->item
, &reversed
);
679 index_fd
= hold_locked_index(lock
, 1);
680 clean
= merge_recursive(&o
, lookup_commit(head
),
681 remoteheads
->item
, reversed
, &result
);
682 if (active_cache_changed
&&
683 (write_cache(index_fd
, active_cache
, active_nr
) ||
684 commit_locked_index(lock
)))
685 die ("unable to write %s", get_index_file());
686 rollback_lock_file(lock
);
687 return clean
? 0 : 1;
689 return try_merge_command(strategy
, 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 int merge_trivial(void)
806 unsigned char result_tree
[20], result_commit
[20];
807 struct commit_list
*parent
= xmalloc(sizeof(*parent
));
809 write_tree_trivial(result_tree
);
810 printf("Wonderful.\n");
811 parent
->item
= lookup_commit(head
);
812 parent
->next
= xmalloc(sizeof(*parent
->next
));
813 parent
->next
->item
= remoteheads
->item
;
814 parent
->next
->next
= NULL
;
815 commit_tree(merge_msg
.buf
, result_tree
, parent
, result_commit
, NULL
);
816 finish(result_commit
, "In-index merge");
821 static int finish_automerge(struct commit_list
*common
,
822 unsigned char *result_tree
,
823 const char *wt_strategy
)
825 struct commit_list
*parents
= NULL
, *j
;
826 struct strbuf buf
= STRBUF_INIT
;
827 unsigned char result_commit
[20];
829 free_commit_list(common
);
830 if (allow_fast_forward
) {
831 parents
= remoteheads
;
832 commit_list_insert(lookup_commit(head
), &parents
);
833 parents
= reduce_heads(parents
);
835 struct commit_list
**pptr
= &parents
;
837 pptr
= &commit_list_insert(lookup_commit(head
),
839 for (j
= remoteheads
; j
; j
= j
->next
)
840 pptr
= &commit_list_insert(j
->item
, pptr
)->next
;
842 free_commit_list(remoteheads
);
843 strbuf_addch(&merge_msg
, '\n');
844 commit_tree(merge_msg
.buf
, result_tree
, parents
, result_commit
, NULL
);
845 strbuf_addf(&buf
, "Merge made by %s.", wt_strategy
);
846 finish(result_commit
, buf
.buf
);
847 strbuf_release(&buf
);
852 static int suggest_conflicts(int renormalizing
)
857 fp
= fopen(git_path("MERGE_MSG"), "a");
859 die_errno("Could not open '%s' for writing",
860 git_path("MERGE_MSG"));
861 fprintf(fp
, "\nConflicts:\n");
862 for (pos
= 0; pos
< active_nr
; pos
++) {
863 struct cache_entry
*ce
= active_cache
[pos
];
866 fprintf(fp
, "\t%s\n", ce
->name
);
867 while (pos
+ 1 < active_nr
&&
869 active_cache
[pos
+ 1]->name
))
874 rerere(allow_rerere_auto
);
875 printf("Automatic merge failed; "
876 "fix conflicts and then commit the result.\n");
880 static struct commit
*is_old_style_invocation(int argc
, const char **argv
)
882 struct commit
*second_token
= NULL
;
884 unsigned char second_sha1
[20];
886 if (get_sha1(argv
[1], second_sha1
))
888 second_token
= lookup_commit_reference_gently(second_sha1
, 0);
890 die("'%s' is not a commit", argv
[1]);
891 if (hashcmp(second_token
->object
.sha1
, head
))
897 static int evaluate_result(void)
902 /* Check how many files differ. */
903 init_revisions(&rev
, "");
904 setup_revisions(0, NULL
, &rev
, NULL
);
905 rev
.diffopt
.output_format
|=
906 DIFF_FORMAT_CALLBACK
;
907 rev
.diffopt
.format_callback
= count_diff_files
;
908 rev
.diffopt
.format_callback_data
= &cnt
;
909 run_diff_files(&rev
, 0);
912 * Check how many unmerged entries are
915 cnt
+= count_unmerged_entries();
921 * Pretend as if the user told us to merge with the tracking
922 * branch we have for the upstream of the current branch
924 static int setup_with_upstream(const char ***argv
)
926 struct branch
*branch
= branch_get(NULL
);
931 die("No current branch.");
933 die("No remote for the current branch.");
934 if (!branch
->merge_nr
)
935 die("No default upstream defined for the current branch.");
937 args
= xcalloc(branch
->merge_nr
+ 1, sizeof(char *));
938 for (i
= 0; i
< branch
->merge_nr
; i
++) {
939 if (!branch
->merge
[i
]->dst
)
940 die("No remote tracking branch for %s from %s",
941 branch
->merge
[i
]->src
, branch
->remote_name
);
942 args
[i
] = branch
->merge
[i
]->dst
;
949 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
951 unsigned char result_tree
[20];
952 struct strbuf buf
= STRBUF_INIT
;
953 const char *head_arg
;
954 int flag
, head_invalid
= 0, i
;
955 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
956 struct commit_list
*common
= NULL
;
957 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
958 struct commit_list
**remotes
= &remoteheads
;
960 if (argc
== 2 && !strcmp(argv
[1], "-h"))
961 usage_with_options(builtin_merge_usage
, builtin_merge_options
);
964 * Check if we are _not_ on a detached HEAD, i.e. if there is a
967 branch
= resolve_ref("HEAD", head
, 0, &flag
);
968 if (branch
&& !prefixcmp(branch
, "refs/heads/"))
970 if (is_null_sha1(head
))
973 git_config(git_merge_config
, NULL
);
976 if (diff_use_color_default
== -1)
977 diff_use_color_default
= git_use_color_default
;
979 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
980 builtin_merge_usage
, 0);
982 if (abort_current_merge
) {
984 const char *nargv
[] = {"reset", "--merge", NULL
};
986 if (!file_exists(git_path("MERGE_HEAD")))
987 die("There is no merge to abort (MERGE_HEAD missing).");
989 /* Invoke 'git reset --merge' */
990 return cmd_reset(nargc
, nargv
, prefix
);
993 if (read_cache_unmerged())
994 die_resolve_conflict("merge");
996 if (file_exists(git_path("MERGE_HEAD"))) {
998 * There is no unmerged entry, don't advise 'git
999 * add/rm <file>', just 'git commit'.
1001 if (advice_resolve_conflict
)
1002 die("You have not concluded your merge (MERGE_HEAD exists).\n"
1003 "Please, commit your changes before you can merge.");
1005 die("You have not concluded your merge (MERGE_HEAD exists).");
1007 resolve_undo_clear();
1013 if (!allow_fast_forward
)
1014 die("You cannot combine --squash with --no-ff.");
1018 if (!allow_fast_forward
&& fast_forward_only
)
1019 die("You cannot combine --no-ff with --ff-only.");
1021 if (!argc
&& !abort_current_merge
&& default_to_upstream
)
1022 argc
= setup_with_upstream(&argv
);
1025 usage_with_options(builtin_merge_usage
,
1026 builtin_merge_options
);
1029 * This could be traditional "merge <msg> HEAD <commit>..." and
1030 * the way we can tell it is to see if the second token is HEAD,
1031 * but some people might have misused the interface and used a
1032 * committish that is the same as HEAD there instead.
1033 * Traditional format never would have "-m" so it is an
1034 * additional safety measure to check for it.
1037 if (!have_message
&& is_old_style_invocation(argc
, argv
)) {
1038 strbuf_addstr(&merge_msg
, argv
[0]);
1042 } else if (head_invalid
) {
1043 struct object
*remote_head
;
1045 * If the merged head is a valid one there is no reason
1046 * to forbid "git merge" into a branch yet to be born.
1047 * We do the same for "git pull".
1050 die("Can merge only exactly one commit into "
1053 die("Squash commit into empty head not supported yet");
1054 if (!allow_fast_forward
)
1055 die("Non-fast-forward commit does not make sense into "
1057 remote_head
= peel_to_type(argv
[0], 0, NULL
, OBJ_COMMIT
);
1059 die("%s - not something we can merge", argv
[0]);
1060 update_ref("initial pull", "HEAD", remote_head
->sha1
, NULL
, 0,
1062 read_empty(remote_head
->sha1
, 0);
1065 struct strbuf merge_names
= STRBUF_INIT
;
1067 /* We are invoked directly as the first-class UI. */
1071 * All the rest are the commits being merged;
1072 * prepare the standard merge summary message to
1073 * be appended to the given message. If remote
1074 * is invalid we will die later in the common
1075 * codepath so we discard the error in this
1078 for (i
= 0; i
< argc
; i
++)
1079 merge_name(argv
[i
], &merge_names
);
1081 if (!have_message
|| shortlog_len
) {
1082 fmt_merge_msg(&merge_names
, &merge_msg
, !have_message
,
1085 strbuf_setlen(&merge_msg
, merge_msg
.len
- 1);
1089 if (head_invalid
|| !argc
)
1090 usage_with_options(builtin_merge_usage
,
1091 builtin_merge_options
);
1093 strbuf_addstr(&buf
, "merge");
1094 for (i
= 0; i
< argc
; i
++)
1095 strbuf_addf(&buf
, " %s", argv
[i
]);
1096 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
1099 for (i
= 0; i
< argc
; i
++) {
1101 struct commit
*commit
;
1103 o
= peel_to_type(argv
[i
], 0, NULL
, OBJ_COMMIT
);
1105 die("%s - not something we can merge", argv
[i
]);
1106 commit
= lookup_commit(o
->sha1
);
1107 commit
->util
= (void *)argv
[i
];
1108 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1110 strbuf_addf(&buf
, "GITHEAD_%s", sha1_to_hex(o
->sha1
));
1111 setenv(buf
.buf
, argv
[i
], 1);
1115 if (!use_strategies
) {
1116 if (!remoteheads
->next
)
1117 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
1119 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
1122 for (i
= 0; i
< use_strategies_nr
; i
++) {
1123 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
1124 allow_fast_forward
= 0;
1125 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
1129 if (!remoteheads
->next
)
1130 common
= get_merge_bases(lookup_commit(head
),
1131 remoteheads
->item
, 1);
1133 struct commit_list
*list
= remoteheads
;
1134 commit_list_insert(lookup_commit(head
), &list
);
1135 common
= get_octopus_merge_bases(list
);
1139 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head
, NULL
, 0,
1143 ; /* No common ancestors found. We need a real merge. */
1144 else if (!remoteheads
->next
&& !common
->next
&&
1145 common
->item
== remoteheads
->item
) {
1147 * If head can reach all the merge then we are up to date.
1148 * but first the most common case of merging one remote.
1150 finish_up_to_date("Already up-to-date.");
1152 } else if (allow_fast_forward
&& !remoteheads
->next
&&
1154 !hashcmp(common
->item
->object
.sha1
, head
)) {
1155 /* Again the most common case of merging one remote. */
1156 struct strbuf msg
= STRBUF_INIT
;
1160 strcpy(hex
, find_unique_abbrev(head
, DEFAULT_ABBREV
));
1163 printf("Updating %s..%s\n",
1165 find_unique_abbrev(remoteheads
->item
->object
.sha1
,
1167 strbuf_addstr(&msg
, "Fast-forward");
1170 " (no commit created; -m option ignored)");
1171 o
= peel_to_type(sha1_to_hex(remoteheads
->item
->object
.sha1
),
1172 0, NULL
, OBJ_COMMIT
);
1176 if (checkout_fast_forward(head
, remoteheads
->item
->object
.sha1
))
1179 finish(o
->sha1
, msg
.buf
);
1182 } else if (!remoteheads
->next
&& common
->next
)
1185 * We are not doing octopus and not fast-forward. Need
1188 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1190 * We are not doing octopus, not fast-forward, and have
1193 refresh_cache(REFRESH_QUIET
);
1194 if (allow_trivial
&& !fast_forward_only
) {
1195 /* See if it is really trivial. */
1196 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1197 printf("Trying really trivial in-index merge...\n");
1198 if (!read_tree_trivial(common
->item
->object
.sha1
,
1199 head
, remoteheads
->item
->object
.sha1
))
1200 return merge_trivial();
1205 * An octopus. If we can reach all the remote we are up
1209 struct commit_list
*j
;
1211 for (j
= remoteheads
; j
; j
= j
->next
) {
1212 struct commit_list
*common_one
;
1215 * Here we *have* to calculate the individual
1216 * merge_bases again, otherwise "git merge HEAD^
1217 * HEAD^^" would be missed.
1219 common_one
= get_merge_bases(lookup_commit(head
),
1221 if (hashcmp(common_one
->item
->object
.sha1
,
1222 j
->item
->object
.sha1
)) {
1228 finish_up_to_date("Already up-to-date. Yeeah!");
1233 if (fast_forward_only
)
1234 die("Not possible to fast-forward, aborting.");
1236 /* We are going to make a new commit. */
1237 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1240 * At this point, we need a real merge. No matter what strategy
1241 * we use, it would operate on the index, possibly affecting the
1242 * working tree, and when resolved cleanly, have the desired
1243 * tree in the index -- this means that the index must be in
1244 * sync with the head commit. The strategies are responsible
1247 if (use_strategies_nr
!= 1) {
1249 * Stash away the local changes so that we can try more
1254 memcpy(stash
, null_sha1
, 20);
1257 for (i
= 0; i
< use_strategies_nr
; i
++) {
1260 printf("Rewinding the tree to pristine...\n");
1263 if (use_strategies_nr
!= 1)
1264 printf("Trying merge strategy %s...\n",
1265 use_strategies
[i
]->name
);
1267 * Remember which strategy left the state in the working
1270 wt_strategy
= use_strategies
[i
]->name
;
1272 ret
= try_merge_strategy(use_strategies
[i
]->name
,
1274 if (!option_commit
&& !ret
) {
1277 * This is necessary here just to avoid writing
1278 * the tree, but later we will *not* exit with
1279 * status code 1 because merge_was_ok is set.
1286 * The backend exits with 1 when conflicts are
1287 * left to be resolved, with 2 when it does not
1288 * handle the given merge at all.
1291 int cnt
= evaluate_result();
1293 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1294 best_strategy
= use_strategies
[i
]->name
;
1304 /* Automerge succeeded. */
1305 write_tree_trivial(result_tree
);
1306 automerge_was_ok
= 1;
1311 * If we have a resulting tree, that means the strategy module
1312 * auto resolved the merge cleanly.
1314 if (automerge_was_ok
)
1315 return finish_automerge(common
, result_tree
, wt_strategy
);
1318 * Pick the result from the best strategy and have the user fix
1321 if (!best_strategy
) {
1323 if (use_strategies_nr
> 1)
1325 "No merge strategy handled the merge.\n");
1327 fprintf(stderr
, "Merge with strategy %s failed.\n",
1328 use_strategies
[0]->name
);
1330 } else if (best_strategy
== wt_strategy
)
1331 ; /* We already have its result in the working tree. */
1333 printf("Rewinding the tree to pristine...\n");
1335 printf("Using the %s to prepare resolving by hand.\n",
1337 try_merge_strategy(best_strategy
, common
, head_arg
);
1344 struct commit_list
*j
;
1346 for (j
= remoteheads
; j
; j
= j
->next
)
1347 strbuf_addf(&buf
, "%s\n",
1348 sha1_to_hex(j
->item
->object
.sha1
));
1349 fd
= open(git_path("MERGE_HEAD"), O_WRONLY
| O_CREAT
, 0666);
1351 die_errno("Could not open '%s' for writing",
1352 git_path("MERGE_HEAD"));
1353 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1354 die_errno("Could not write to '%s'", git_path("MERGE_HEAD"));
1356 strbuf_addch(&merge_msg
, '\n');
1357 fd
= open(git_path("MERGE_MSG"), O_WRONLY
| O_CREAT
, 0666);
1359 die_errno("Could not open '%s' for writing",
1360 git_path("MERGE_MSG"));
1361 if (write_in_full(fd
, merge_msg
.buf
, merge_msg
.len
) !=
1363 die_errno("Could not write to '%s'", git_path("MERGE_MSG"));
1365 fd
= open(git_path("MERGE_MODE"), O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
1367 die_errno("Could not open '%s' for writing",
1368 git_path("MERGE_MODE"));
1370 if (!allow_fast_forward
)
1371 strbuf_addf(&buf
, "no-ff");
1372 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1373 die_errno("Could not write to '%s'", git_path("MERGE_MODE"));
1378 fprintf(stderr
, "Automatic merge went well; "
1379 "stopped before committing as requested\n");
1382 return suggest_conflicts(option_renormalize
);