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"
28 #define DEFAULT_TWOHEAD (1<<0)
29 #define DEFAULT_OCTOPUS (1<<1)
30 #define NO_FAST_FORWARD (1<<2)
31 #define NO_TRIVIAL (1<<3)
38 static const char * const builtin_merge_usage
[] = {
39 "git merge [options] <remote>...",
40 "git merge [options] <msg> HEAD <remote>",
44 static int show_diffstat
= 1, option_log
, squash
;
45 static int option_commit
= 1, allow_fast_forward
= 1;
46 static int fast_forward_only
;
47 static int allow_trivial
= 1, have_message
;
48 static struct strbuf merge_msg
;
49 static struct commit_list
*remoteheads
;
50 static unsigned char head
[20], stash
[20];
51 static struct strategy
**use_strategies
;
52 static size_t use_strategies_nr
, use_strategies_alloc
;
53 static const char **xopts
;
54 static size_t xopts_nr
, xopts_alloc
;
55 static const char *branch
;
58 static struct strategy all_strategy
[] = {
59 { "recursive", DEFAULT_TWOHEAD
| NO_TRIVIAL
},
60 { "octopus", DEFAULT_OCTOPUS
},
62 { "ours", NO_FAST_FORWARD
| NO_TRIVIAL
},
63 { "subtree", NO_FAST_FORWARD
| NO_TRIVIAL
},
66 static const char *pull_twohead
, *pull_octopus
;
68 static int option_parse_message(const struct option
*opt
,
69 const char *arg
, int unset
)
71 struct strbuf
*buf
= opt
->value
;
74 strbuf_setlen(buf
, 0);
76 strbuf_addf(buf
, "%s\n\n", arg
);
79 return error("switch `m' requires a value");
83 static struct strategy
*get_strategy(const char *name
)
87 static struct cmdnames main_cmds
, other_cmds
;
93 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
94 if (!strcmp(name
, all_strategy
[i
].name
))
95 return &all_strategy
[i
];
98 struct cmdnames not_strategies
;
101 memset(¬_strategies
, 0, sizeof(struct cmdnames
));
102 load_command_list("git-merge-", &main_cmds
, &other_cmds
);
103 for (i
= 0; i
< main_cmds
.cnt
; i
++) {
105 struct cmdname
*ent
= main_cmds
.names
[i
];
106 for (j
= 0; j
< ARRAY_SIZE(all_strategy
); j
++)
107 if (!strncmp(ent
->name
, all_strategy
[j
].name
, ent
->len
)
108 && !all_strategy
[j
].name
[ent
->len
])
111 add_cmdname(¬_strategies
, ent
->name
, ent
->len
);
113 exclude_cmds(&main_cmds
, ¬_strategies
);
115 if (!is_in_cmdlist(&main_cmds
, name
) && !is_in_cmdlist(&other_cmds
, name
)) {
116 fprintf(stderr
, "Could not find merge strategy '%s'.\n", name
);
117 fprintf(stderr
, "Available strategies are:");
118 for (i
= 0; i
< main_cmds
.cnt
; i
++)
119 fprintf(stderr
, " %s", main_cmds
.names
[i
]->name
);
120 fprintf(stderr
, ".\n");
121 if (other_cmds
.cnt
) {
122 fprintf(stderr
, "Available custom strategies are:");
123 for (i
= 0; i
< other_cmds
.cnt
; i
++)
124 fprintf(stderr
, " %s", other_cmds
.names
[i
]->name
);
125 fprintf(stderr
, ".\n");
130 ret
= xcalloc(1, sizeof(struct strategy
));
131 ret
->name
= xstrdup(name
);
135 static void append_strategy(struct strategy
*s
)
137 ALLOC_GROW(use_strategies
, use_strategies_nr
+ 1, use_strategies_alloc
);
138 use_strategies
[use_strategies_nr
++] = s
;
141 static int option_parse_strategy(const struct option
*opt
,
142 const char *name
, int unset
)
147 append_strategy(get_strategy(name
));
151 static int option_parse_x(const struct option
*opt
,
152 const char *arg
, int unset
)
157 ALLOC_GROW(xopts
, xopts_nr
+ 1, xopts_alloc
);
158 xopts
[xopts_nr
++] = xstrdup(arg
);
162 static int option_parse_n(const struct option
*opt
,
163 const char *arg
, int unset
)
165 show_diffstat
= unset
;
169 static struct option builtin_merge_options
[] = {
170 { OPTION_CALLBACK
, 'n', NULL
, NULL
, NULL
,
171 "do not show a diffstat at the end of the merge",
172 PARSE_OPT_NOARG
, option_parse_n
},
173 OPT_BOOLEAN(0, "stat", &show_diffstat
,
174 "show a diffstat at the end of the merge"),
175 OPT_BOOLEAN(0, "summary", &show_diffstat
, "(synonym to --stat)"),
176 OPT_BOOLEAN(0, "log", &option_log
,
177 "add list of one-line log to merge commit message"),
178 OPT_BOOLEAN(0, "squash", &squash
,
179 "create a single commit instead of doing a merge"),
180 OPT_BOOLEAN(0, "commit", &option_commit
,
181 "perform a commit if the merge succeeds (default)"),
182 OPT_BOOLEAN(0, "ff", &allow_fast_forward
,
183 "allow fast-forward (default)"),
184 OPT_BOOLEAN(0, "ff-only", &fast_forward_only
,
185 "abort if fast-forward is not possible"),
186 OPT_CALLBACK('s', "strategy", &use_strategies
, "strategy",
187 "merge strategy to use", option_parse_strategy
),
188 OPT_CALLBACK('X', "strategy-option", &xopts
, "option=value",
189 "option for selected merge strategy", option_parse_x
),
190 OPT_CALLBACK('m', "message", &merge_msg
, "message",
191 "message to be used for the merge commit (if any)",
192 option_parse_message
),
193 OPT__VERBOSITY(&verbosity
),
197 /* Cleans up metadata that is uninteresting after a succeeded merge. */
198 static void drop_save(void)
200 unlink(git_path("MERGE_HEAD"));
201 unlink(git_path("MERGE_MSG"));
202 unlink(git_path("MERGE_MODE"));
205 static void save_state(void)
208 struct child_process cp
;
209 struct strbuf buffer
= STRBUF_INIT
;
210 const char *argv
[] = {"stash", "create", NULL
};
212 memset(&cp
, 0, sizeof(cp
));
217 if (start_command(&cp
))
218 die("could not run stash.");
219 len
= strbuf_read(&buffer
, cp
.out
, 1024);
222 if (finish_command(&cp
) || len
< 0)
226 strbuf_setlen(&buffer
, buffer
.len
-1);
227 if (get_sha1(buffer
.buf
, stash
))
228 die("not a valid object: %s", buffer
.buf
);
231 static void reset_hard(unsigned const char *sha1
, int verbose
)
236 args
[i
++] = "read-tree";
239 args
[i
++] = "--reset";
241 args
[i
++] = sha1_to_hex(sha1
);
244 if (run_command_v_opt(args
, RUN_GIT_CMD
))
245 die("read-tree failed");
248 static void restore_state(void)
250 struct strbuf sb
= STRBUF_INIT
;
251 const char *args
[] = { "stash", "apply", NULL
, NULL
};
253 if (is_null_sha1(stash
))
258 args
[2] = sha1_to_hex(stash
);
261 * It is OK to ignore error here, for example when there was
262 * nothing to restore.
264 run_command_v_opt(args
, RUN_GIT_CMD
);
267 refresh_cache(REFRESH_QUIET
);
270 /* This is called when no merge was necessary. */
271 static void finish_up_to_date(const char *msg
)
274 printf("%s%s\n", squash
? " (nothing to squash)" : "", msg
);
278 static void squash_message(void)
281 struct commit
*commit
;
282 struct strbuf out
= STRBUF_INIT
;
283 struct commit_list
*j
;
285 struct pretty_print_context ctx
= {0};
287 printf("Squash commit -- not updating HEAD\n");
288 fd
= open(git_path("SQUASH_MSG"), O_WRONLY
| O_CREAT
, 0666);
290 die_errno("Could not write to '%s'", git_path("SQUASH_MSG"));
292 init_revisions(&rev
, NULL
);
293 rev
.ignore_merges
= 1;
294 rev
.commit_format
= CMIT_FMT_MEDIUM
;
296 commit
= lookup_commit(head
);
297 commit
->object
.flags
|= UNINTERESTING
;
298 add_pending_object(&rev
, &commit
->object
, NULL
);
300 for (j
= remoteheads
; j
; j
= j
->next
)
301 add_pending_object(&rev
, &j
->item
->object
, NULL
);
303 setup_revisions(0, NULL
, &rev
, NULL
);
304 if (prepare_revision_walk(&rev
))
305 die("revision walk setup failed");
307 ctx
.abbrev
= rev
.abbrev
;
308 ctx
.date_mode
= rev
.date_mode
;
310 strbuf_addstr(&out
, "Squashed commit of the following:\n");
311 while ((commit
= get_revision(&rev
)) != NULL
) {
312 strbuf_addch(&out
, '\n');
313 strbuf_addf(&out
, "commit %s\n",
314 sha1_to_hex(commit
->object
.sha1
));
315 pretty_print_commit(rev
.commit_format
, commit
, &out
, &ctx
);
317 if (write(fd
, out
.buf
, out
.len
) < 0)
318 die_errno("Writing SQUASH_MSG");
320 die_errno("Finishing SQUASH_MSG");
321 strbuf_release(&out
);
324 static void finish(const unsigned char *new_head
, const char *msg
)
326 struct strbuf reflog_message
= STRBUF_INIT
;
329 strbuf_addstr(&reflog_message
, getenv("GIT_REFLOG_ACTION"));
333 strbuf_addf(&reflog_message
, "%s: %s",
334 getenv("GIT_REFLOG_ACTION"), msg
);
339 if (verbosity
>= 0 && !merge_msg
.len
)
340 printf("No merge message -- not updating HEAD\n");
342 const char *argv_gc_auto
[] = { "gc", "--auto", NULL
};
343 update_ref(reflog_message
.buf
, "HEAD",
347 * We ignore errors in 'gc --auto', since the
348 * user should see them.
350 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
353 if (new_head
&& show_diffstat
) {
354 struct diff_options opts
;
356 opts
.output_format
|=
357 DIFF_FORMAT_SUMMARY
| DIFF_FORMAT_DIFFSTAT
;
358 opts
.detect_rename
= DIFF_DETECT_RENAME
;
359 if (diff_use_color_default
> 0)
360 DIFF_OPT_SET(&opts
, COLOR_DIFF
);
361 if (diff_setup_done(&opts
) < 0)
362 die("diff_setup_done failed");
363 diff_tree_sha1(head
, new_head
, "", &opts
);
368 /* Run a post-merge hook */
369 run_hook(NULL
, "post-merge", squash
? "1" : "0", NULL
);
371 strbuf_release(&reflog_message
);
374 /* Get the name for the merge commit's message. */
375 static void merge_name(const char *remote
, struct strbuf
*msg
)
377 struct object
*remote_head
;
378 unsigned char branch_head
[20], buf_sha
[20];
379 struct strbuf buf
= STRBUF_INIT
;
380 struct strbuf bname
= STRBUF_INIT
;
385 strbuf_branchname(&bname
, remote
);
388 memset(branch_head
, 0, sizeof(branch_head
));
389 remote_head
= peel_to_type(remote
, 0, NULL
, OBJ_COMMIT
);
391 die("'%s' does not point to a commit", remote
);
393 if (dwim_ref(remote
, strlen(remote
), branch_head
, &found_ref
) > 0) {
394 if (!prefixcmp(found_ref
, "refs/heads/")) {
395 strbuf_addf(msg
, "%s\t\tbranch '%s' of .\n",
396 sha1_to_hex(branch_head
), remote
);
399 if (!prefixcmp(found_ref
, "refs/remotes/")) {
400 strbuf_addf(msg
, "%s\t\tremote branch '%s' of .\n",
401 sha1_to_hex(branch_head
), remote
);
406 /* See if remote matches <name>^^^.. or <name>~<number> */
407 for (len
= 0, ptr
= remote
+ strlen(remote
);
408 remote
< ptr
&& ptr
[-1] == '^';
415 ptr
= strrchr(remote
, '~');
417 int seen_nonzero
= 0;
420 while (*++ptr
&& isdigit(*ptr
)) {
421 seen_nonzero
|= (*ptr
!= '0');
425 len
= 0; /* not ...~<number> */
426 else if (seen_nonzero
)
429 early
= 1; /* "name~" is "name~1"! */
433 struct strbuf truname
= STRBUF_INIT
;
434 strbuf_addstr(&truname
, "refs/heads/");
435 strbuf_addstr(&truname
, remote
);
436 strbuf_setlen(&truname
, truname
.len
- len
);
437 if (resolve_ref(truname
.buf
, buf_sha
, 0, NULL
)) {
439 "%s\t\tbranch '%s'%s of .\n",
440 sha1_to_hex(remote_head
->sha1
),
442 (early
? " (early part)" : ""));
443 strbuf_release(&truname
);
448 if (!strcmp(remote
, "FETCH_HEAD") &&
449 !access(git_path("FETCH_HEAD"), R_OK
)) {
451 struct strbuf line
= STRBUF_INIT
;
454 fp
= fopen(git_path("FETCH_HEAD"), "r");
456 die_errno("could not open '%s' for reading",
457 git_path("FETCH_HEAD"));
458 strbuf_getline(&line
, fp
, '\n');
460 ptr
= strstr(line
.buf
, "\tnot-for-merge\t");
462 strbuf_remove(&line
, ptr
-line
.buf
+1, 13);
463 strbuf_addbuf(msg
, &line
);
464 strbuf_release(&line
);
467 strbuf_addf(msg
, "%s\t\tcommit '%s'\n",
468 sha1_to_hex(remote_head
->sha1
), remote
);
470 strbuf_release(&buf
);
471 strbuf_release(&bname
);
474 static int git_merge_config(const char *k
, const char *v
, void *cb
)
476 if (branch
&& !prefixcmp(k
, "branch.") &&
477 !prefixcmp(k
+ 7, branch
) &&
478 !strcmp(k
+ 7 + strlen(branch
), ".mergeoptions")) {
484 argc
= split_cmdline(buf
, &argv
);
486 die("Bad branch.%s.mergeoptions string", branch
);
487 argv
= xrealloc(argv
, sizeof(*argv
) * (argc
+ 2));
488 memmove(argv
+ 1, argv
, sizeof(*argv
) * (argc
+ 1));
490 parse_options(argc
, argv
, NULL
, builtin_merge_options
,
491 builtin_merge_usage
, 0);
495 if (!strcmp(k
, "merge.diffstat") || !strcmp(k
, "merge.stat"))
496 show_diffstat
= git_config_bool(k
, v
);
497 else if (!strcmp(k
, "pull.twohead"))
498 return git_config_string(&pull_twohead
, k
, v
);
499 else if (!strcmp(k
, "pull.octopus"))
500 return git_config_string(&pull_octopus
, k
, v
);
501 else if (!strcmp(k
, "merge.log") || !strcmp(k
, "merge.summary"))
502 option_log
= git_config_bool(k
, v
);
503 return git_diff_ui_config(k
, v
, cb
);
506 static int read_tree_trivial(unsigned char *common
, unsigned char *head
,
510 struct tree
*trees
[MAX_UNPACK_TREES
];
511 struct tree_desc t
[MAX_UNPACK_TREES
];
512 struct unpack_trees_options opts
;
514 memset(&opts
, 0, sizeof(opts
));
516 opts
.src_index
= &the_index
;
517 opts
.dst_index
= &the_index
;
519 opts
.verbose_update
= 1;
520 opts
.trivial_merges_only
= 1;
522 trees
[nr_trees
] = parse_tree_indirect(common
);
523 if (!trees
[nr_trees
++])
525 trees
[nr_trees
] = parse_tree_indirect(head
);
526 if (!trees
[nr_trees
++])
528 trees
[nr_trees
] = parse_tree_indirect(one
);
529 if (!trees
[nr_trees
++])
531 opts
.fn
= threeway_merge
;
532 cache_tree_free(&active_cache_tree
);
533 for (i
= 0; i
< nr_trees
; i
++) {
534 parse_tree(trees
[i
]);
535 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
537 if (unpack_trees(nr_trees
, t
, &opts
))
542 static void write_tree_trivial(unsigned char *sha1
)
544 if (write_cache_as_tree(sha1
, 0, NULL
))
545 die("git write-tree failed to write a tree");
548 static int try_merge_strategy(const char *strategy
, struct commit_list
*common
,
549 const char *head_arg
)
552 int i
= 0, x
= 0, ret
;
553 struct commit_list
*j
;
554 struct strbuf buf
= STRBUF_INIT
;
556 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
558 index_fd
= hold_locked_index(lock
, 1);
559 refresh_cache(REFRESH_QUIET
);
560 if (active_cache_changed
&&
561 (write_cache(index_fd
, active_cache
, active_nr
) ||
562 commit_locked_index(lock
)))
563 return error("Unable to write index.");
564 rollback_lock_file(lock
);
566 if (!strcmp(strategy
, "recursive") || !strcmp(strategy
, "subtree")) {
568 struct commit
*result
;
569 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
571 struct commit_list
*reversed
= NULL
;
572 struct merge_options o
;
574 if (remoteheads
->next
) {
575 error("Not handling anything other than two heads merge.");
579 init_merge_options(&o
);
580 if (!strcmp(strategy
, "subtree"))
581 o
.recursive_variant
= MERGE_RECURSIVE_SUBTREE
;
583 for (x
= 0; x
< xopts_nr
; x
++) {
584 if (!strcmp(xopts
[x
], "ours"))
585 o
.recursive_variant
= MERGE_RECURSIVE_OURS
;
586 else if (!strcmp(xopts
[x
], "theirs"))
587 o
.recursive_variant
= MERGE_RECURSIVE_THEIRS
;
588 else if (!strcmp(xopts
[x
], "subtree"))
589 o
.recursive_variant
= MERGE_RECURSIVE_SUBTREE
;
591 die("Unknown option for merge-recursive: -X%s", xopts
[x
]);
594 o
.branch1
= head_arg
;
595 o
.branch2
= remoteheads
->item
->util
;
597 for (j
= common
; j
; j
= j
->next
)
598 commit_list_insert(j
->item
, &reversed
);
600 index_fd
= hold_locked_index(lock
, 1);
601 clean
= merge_recursive(&o
, lookup_commit(head
),
602 remoteheads
->item
, reversed
, &result
);
603 if (active_cache_changed
&&
604 (write_cache(index_fd
, active_cache
, active_nr
) ||
605 commit_locked_index(lock
)))
606 die ("unable to write %s", get_index_file());
607 rollback_lock_file(lock
);
608 return clean
? 0 : 1;
610 args
= xmalloc((4 + xopts_nr
+ commit_list_count(common
) +
611 commit_list_count(remoteheads
)) * sizeof(char *));
612 strbuf_addf(&buf
, "merge-%s", strategy
);
614 for (x
= 0; x
< xopts_nr
; x
++) {
615 char *s
= xmalloc(strlen(xopts
[x
])+2+1);
617 strcpy(s
+2, xopts
[x
]);
620 for (j
= common
; j
; j
= j
->next
)
621 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
623 args
[i
++] = head_arg
;
624 for (j
= remoteheads
; j
; j
= j
->next
)
625 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
627 ret
= run_command_v_opt(args
, RUN_GIT_CMD
);
628 strbuf_release(&buf
);
630 for (x
= 0; x
< xopts_nr
; x
++)
631 free((void *)args
[i
++]);
632 for (j
= common
; j
; j
= j
->next
)
633 free((void *)args
[i
++]);
635 for (j
= remoteheads
; j
; j
= j
->next
)
636 free((void *)args
[i
++]);
639 if (read_cache() < 0)
640 die("failed to read the cache");
645 static void count_diff_files(struct diff_queue_struct
*q
,
646 struct diff_options
*opt
, void *data
)
653 static int count_unmerged_entries(void)
655 const struct index_state
*state
= &the_index
;
658 for (i
= 0; i
< state
->cache_nr
; i
++)
659 if (ce_stage(state
->cache
[i
]))
665 static int checkout_fast_forward(unsigned char *head
, unsigned char *remote
)
667 struct tree
*trees
[MAX_UNPACK_TREES
];
668 struct unpack_trees_options opts
;
669 struct tree_desc t
[MAX_UNPACK_TREES
];
670 int i
, fd
, nr_trees
= 0;
671 struct dir_struct dir
;
672 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
674 refresh_cache(REFRESH_QUIET
);
676 fd
= hold_locked_index(lock_file
, 1);
678 memset(&trees
, 0, sizeof(trees
));
679 memset(&opts
, 0, sizeof(opts
));
680 memset(&t
, 0, sizeof(t
));
681 memset(&dir
, 0, sizeof(dir
));
682 dir
.flags
|= DIR_SHOW_IGNORED
;
683 dir
.exclude_per_dir
= ".gitignore";
687 opts
.src_index
= &the_index
;
688 opts
.dst_index
= &the_index
;
690 opts
.verbose_update
= 1;
692 opts
.fn
= twoway_merge
;
694 trees
[nr_trees
] = parse_tree_indirect(head
);
695 if (!trees
[nr_trees
++])
697 trees
[nr_trees
] = parse_tree_indirect(remote
);
698 if (!trees
[nr_trees
++])
700 for (i
= 0; i
< nr_trees
; i
++) {
701 parse_tree(trees
[i
]);
702 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
704 if (unpack_trees(nr_trees
, t
, &opts
))
706 if (write_cache(fd
, active_cache
, active_nr
) ||
707 commit_locked_index(lock_file
))
708 die("unable to write new index file");
712 static void split_merge_strategies(const char *string
, struct strategy
**list
,
720 buf
= xstrdup(string
);
725 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
726 (*list
)[(*nr
)++].name
= xstrdup(q
);
731 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
732 (*list
)[(*nr
)++].name
= xstrdup(q
);
738 static void add_strategies(const char *string
, unsigned attr
)
740 struct strategy
*list
= NULL
;
741 int list_alloc
= 0, list_nr
= 0, i
;
743 memset(&list
, 0, sizeof(list
));
744 split_merge_strategies(string
, &list
, &list_nr
, &list_alloc
);
746 for (i
= 0; i
< list_nr
; i
++)
747 append_strategy(get_strategy(list
[i
].name
));
750 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
751 if (all_strategy
[i
].attr
& attr
)
752 append_strategy(&all_strategy
[i
]);
756 static int merge_trivial(void)
758 unsigned char result_tree
[20], result_commit
[20];
759 struct commit_list
*parent
= xmalloc(sizeof(*parent
));
761 write_tree_trivial(result_tree
);
762 printf("Wonderful.\n");
763 parent
->item
= lookup_commit(head
);
764 parent
->next
= xmalloc(sizeof(*parent
->next
));
765 parent
->next
->item
= remoteheads
->item
;
766 parent
->next
->next
= NULL
;
767 commit_tree(merge_msg
.buf
, result_tree
, parent
, result_commit
, NULL
);
768 finish(result_commit
, "In-index merge");
773 static int finish_automerge(struct commit_list
*common
,
774 unsigned char *result_tree
,
775 const char *wt_strategy
)
777 struct commit_list
*parents
= NULL
, *j
;
778 struct strbuf buf
= STRBUF_INIT
;
779 unsigned char result_commit
[20];
781 free_commit_list(common
);
782 if (allow_fast_forward
) {
783 parents
= remoteheads
;
784 commit_list_insert(lookup_commit(head
), &parents
);
785 parents
= reduce_heads(parents
);
787 struct commit_list
**pptr
= &parents
;
789 pptr
= &commit_list_insert(lookup_commit(head
),
791 for (j
= remoteheads
; j
; j
= j
->next
)
792 pptr
= &commit_list_insert(j
->item
, pptr
)->next
;
794 free_commit_list(remoteheads
);
795 strbuf_addch(&merge_msg
, '\n');
796 commit_tree(merge_msg
.buf
, result_tree
, parents
, result_commit
, NULL
);
797 strbuf_addf(&buf
, "Merge made by %s.", wt_strategy
);
798 finish(result_commit
, buf
.buf
);
799 strbuf_release(&buf
);
804 static int suggest_conflicts(void)
809 fp
= fopen(git_path("MERGE_MSG"), "a");
811 die_errno("Could not open '%s' for writing",
812 git_path("MERGE_MSG"));
813 fprintf(fp
, "\nConflicts:\n");
814 for (pos
= 0; pos
< active_nr
; pos
++) {
815 struct cache_entry
*ce
= active_cache
[pos
];
818 fprintf(fp
, "\t%s\n", ce
->name
);
819 while (pos
+ 1 < active_nr
&&
821 active_cache
[pos
+ 1]->name
))
827 printf("Automatic merge failed; "
828 "fix conflicts and then commit the result.\n");
832 static struct commit
*is_old_style_invocation(int argc
, const char **argv
)
834 struct commit
*second_token
= NULL
;
836 unsigned char second_sha1
[20];
838 if (get_sha1(argv
[1], second_sha1
))
840 second_token
= lookup_commit_reference_gently(second_sha1
, 0);
842 die("'%s' is not a commit", argv
[1]);
843 if (hashcmp(second_token
->object
.sha1
, head
))
849 static int evaluate_result(void)
854 /* Check how many files differ. */
855 init_revisions(&rev
, "");
856 setup_revisions(0, NULL
, &rev
, NULL
);
857 rev
.diffopt
.output_format
|=
858 DIFF_FORMAT_CALLBACK
;
859 rev
.diffopt
.format_callback
= count_diff_files
;
860 rev
.diffopt
.format_callback_data
= &cnt
;
861 run_diff_files(&rev
, 0);
864 * Check how many unmerged entries are
867 cnt
+= count_unmerged_entries();
872 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
874 unsigned char result_tree
[20];
875 struct strbuf buf
= STRBUF_INIT
;
876 const char *head_arg
;
877 int flag
, head_invalid
= 0, i
;
878 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
879 struct commit_list
*common
= NULL
;
880 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
881 struct commit_list
**remotes
= &remoteheads
;
883 if (file_exists(git_path("MERGE_HEAD")))
884 die("You have not concluded your merge. (MERGE_HEAD exists)");
885 if (read_cache_unmerged())
886 die("You are in the middle of a conflicted merge."
887 " (index unmerged)");
890 * Check if we are _not_ on a detached HEAD, i.e. if there is a
893 branch
= resolve_ref("HEAD", head
, 0, &flag
);
894 if (branch
&& !prefixcmp(branch
, "refs/heads/"))
896 if (is_null_sha1(head
))
899 git_config(git_merge_config
, NULL
);
902 if (diff_use_color_default
== -1)
903 diff_use_color_default
= git_use_color_default
;
905 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
906 builtin_merge_usage
, 0);
911 if (!allow_fast_forward
)
912 die("You cannot combine --squash with --no-ff.");
916 if (!allow_fast_forward
&& fast_forward_only
)
917 die("You cannot combine --no-ff with --ff-only.");
920 usage_with_options(builtin_merge_usage
,
921 builtin_merge_options
);
924 * This could be traditional "merge <msg> HEAD <commit>..." and
925 * the way we can tell it is to see if the second token is HEAD,
926 * but some people might have misused the interface and used a
927 * committish that is the same as HEAD there instead.
928 * Traditional format never would have "-m" so it is an
929 * additional safety measure to check for it.
932 if (!have_message
&& is_old_style_invocation(argc
, argv
)) {
933 strbuf_addstr(&merge_msg
, argv
[0]);
937 } else if (head_invalid
) {
938 struct object
*remote_head
;
940 * If the merged head is a valid one there is no reason
941 * to forbid "git merge" into a branch yet to be born.
942 * We do the same for "git pull".
945 die("Can merge only exactly one commit into "
948 die("Squash commit into empty head not supported yet");
949 if (!allow_fast_forward
)
950 die("Non-fast-forward commit does not make sense into "
952 remote_head
= peel_to_type(argv
[0], 0, NULL
, OBJ_COMMIT
);
954 die("%s - not something we can merge", argv
[0]);
955 update_ref("initial pull", "HEAD", remote_head
->sha1
, NULL
, 0,
957 reset_hard(remote_head
->sha1
, 0);
960 struct strbuf msg
= STRBUF_INIT
;
962 /* We are invoked directly as the first-class UI. */
966 * All the rest are the commits being merged;
967 * prepare the standard merge summary message to
968 * be appended to the given message. If remote
969 * is invalid we will die later in the common
970 * codepath so we discard the error in this
973 for (i
= 0; i
< argc
; i
++)
974 merge_name(argv
[i
], &msg
);
975 fmt_merge_msg(option_log
, &msg
, &merge_msg
);
977 strbuf_setlen(&merge_msg
, merge_msg
.len
-1);
980 if (head_invalid
|| !argc
)
981 usage_with_options(builtin_merge_usage
,
982 builtin_merge_options
);
984 strbuf_addstr(&buf
, "merge");
985 for (i
= 0; i
< argc
; i
++)
986 strbuf_addf(&buf
, " %s", argv
[i
]);
987 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
990 for (i
= 0; i
< argc
; i
++) {
992 struct commit
*commit
;
994 o
= peel_to_type(argv
[i
], 0, NULL
, OBJ_COMMIT
);
996 die("%s - not something we can merge", argv
[i
]);
997 commit
= lookup_commit(o
->sha1
);
998 commit
->util
= (void *)argv
[i
];
999 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1001 strbuf_addf(&buf
, "GITHEAD_%s", sha1_to_hex(o
->sha1
));
1002 setenv(buf
.buf
, argv
[i
], 1);
1006 if (!use_strategies
) {
1007 if (!remoteheads
->next
)
1008 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
1010 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
1013 for (i
= 0; i
< use_strategies_nr
; i
++) {
1014 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
1015 allow_fast_forward
= 0;
1016 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
1020 if (!remoteheads
->next
)
1021 common
= get_merge_bases(lookup_commit(head
),
1022 remoteheads
->item
, 1);
1024 struct commit_list
*list
= remoteheads
;
1025 commit_list_insert(lookup_commit(head
), &list
);
1026 common
= get_octopus_merge_bases(list
);
1030 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head
, NULL
, 0,
1034 ; /* No common ancestors found. We need a real merge. */
1035 else if (!remoteheads
->next
&& !common
->next
&&
1036 common
->item
== remoteheads
->item
) {
1038 * If head can reach all the merge then we are up to date.
1039 * but first the most common case of merging one remote.
1041 finish_up_to_date("Already up-to-date.");
1043 } else if (allow_fast_forward
&& !remoteheads
->next
&&
1045 !hashcmp(common
->item
->object
.sha1
, head
)) {
1046 /* Again the most common case of merging one remote. */
1047 struct strbuf msg
= STRBUF_INIT
;
1051 strcpy(hex
, find_unique_abbrev(head
, DEFAULT_ABBREV
));
1054 printf("Updating %s..%s\n",
1056 find_unique_abbrev(remoteheads
->item
->object
.sha1
,
1058 strbuf_addstr(&msg
, "Fast-forward");
1061 " (no commit created; -m option ignored)");
1062 o
= peel_to_type(sha1_to_hex(remoteheads
->item
->object
.sha1
),
1063 0, NULL
, OBJ_COMMIT
);
1067 if (checkout_fast_forward(head
, remoteheads
->item
->object
.sha1
))
1070 finish(o
->sha1
, msg
.buf
);
1073 } else if (!remoteheads
->next
&& common
->next
)
1076 * We are not doing octopus and not fast-forward. Need
1079 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1081 * We are not doing octopus, not fast-forward, and have
1084 refresh_cache(REFRESH_QUIET
);
1085 if (allow_trivial
&& !fast_forward_only
) {
1086 /* See if it is really trivial. */
1087 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1088 printf("Trying really trivial in-index merge...\n");
1089 if (!read_tree_trivial(common
->item
->object
.sha1
,
1090 head
, remoteheads
->item
->object
.sha1
))
1091 return merge_trivial();
1096 * An octopus. If we can reach all the remote we are up
1100 struct commit_list
*j
;
1102 for (j
= remoteheads
; j
; j
= j
->next
) {
1103 struct commit_list
*common_one
;
1106 * Here we *have* to calculate the individual
1107 * merge_bases again, otherwise "git merge HEAD^
1108 * HEAD^^" would be missed.
1110 common_one
= get_merge_bases(lookup_commit(head
),
1112 if (hashcmp(common_one
->item
->object
.sha1
,
1113 j
->item
->object
.sha1
)) {
1119 finish_up_to_date("Already up-to-date. Yeeah!");
1124 if (fast_forward_only
)
1125 die("Not possible to fast-forward, aborting.");
1127 /* We are going to make a new commit. */
1128 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1131 * At this point, we need a real merge. No matter what strategy
1132 * we use, it would operate on the index, possibly affecting the
1133 * working tree, and when resolved cleanly, have the desired
1134 * tree in the index -- this means that the index must be in
1135 * sync with the head commit. The strategies are responsible
1138 if (use_strategies_nr
!= 1) {
1140 * Stash away the local changes so that we can try more
1145 memcpy(stash
, null_sha1
, 20);
1148 for (i
= 0; i
< use_strategies_nr
; i
++) {
1151 printf("Rewinding the tree to pristine...\n");
1154 if (use_strategies_nr
!= 1)
1155 printf("Trying merge strategy %s...\n",
1156 use_strategies
[i
]->name
);
1158 * Remember which strategy left the state in the working
1161 wt_strategy
= use_strategies
[i
]->name
;
1163 ret
= try_merge_strategy(use_strategies
[i
]->name
,
1165 if (!option_commit
&& !ret
) {
1168 * This is necessary here just to avoid writing
1169 * the tree, but later we will *not* exit with
1170 * status code 1 because merge_was_ok is set.
1177 * The backend exits with 1 when conflicts are
1178 * left to be resolved, with 2 when it does not
1179 * handle the given merge at all.
1182 int cnt
= evaluate_result();
1184 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1185 best_strategy
= use_strategies
[i
]->name
;
1195 /* Automerge succeeded. */
1196 write_tree_trivial(result_tree
);
1197 automerge_was_ok
= 1;
1202 * If we have a resulting tree, that means the strategy module
1203 * auto resolved the merge cleanly.
1205 if (automerge_was_ok
)
1206 return finish_automerge(common
, result_tree
, wt_strategy
);
1209 * Pick the result from the best strategy and have the user fix
1212 if (!best_strategy
) {
1214 if (use_strategies_nr
> 1)
1216 "No merge strategy handled the merge.\n");
1218 fprintf(stderr
, "Merge with strategy %s failed.\n",
1219 use_strategies
[0]->name
);
1221 } else if (best_strategy
== wt_strategy
)
1222 ; /* We already have its result in the working tree. */
1224 printf("Rewinding the tree to pristine...\n");
1226 printf("Using the %s to prepare resolving by hand.\n",
1228 try_merge_strategy(best_strategy
, common
, head_arg
);
1235 struct commit_list
*j
;
1237 for (j
= remoteheads
; j
; j
= j
->next
)
1238 strbuf_addf(&buf
, "%s\n",
1239 sha1_to_hex(j
->item
->object
.sha1
));
1240 fd
= open(git_path("MERGE_HEAD"), O_WRONLY
| O_CREAT
, 0666);
1242 die_errno("Could not open '%s' for writing",
1243 git_path("MERGE_HEAD"));
1244 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1245 die_errno("Could not write to '%s'", git_path("MERGE_HEAD"));
1247 strbuf_addch(&merge_msg
, '\n');
1248 fd
= open(git_path("MERGE_MSG"), O_WRONLY
| O_CREAT
, 0666);
1250 die_errno("Could not open '%s' for writing",
1251 git_path("MERGE_MSG"));
1252 if (write_in_full(fd
, merge_msg
.buf
, merge_msg
.len
) !=
1254 die_errno("Could not write to '%s'", git_path("MERGE_MSG"));
1256 fd
= open(git_path("MERGE_MODE"), O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
1258 die_errno("Could not open '%s' for writing",
1259 git_path("MERGE_MODE"));
1261 if (!allow_fast_forward
)
1262 strbuf_addf(&buf
, "no-ff");
1263 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1264 die_errno("Could not write to '%s'", git_path("MERGE_MODE"));
1269 fprintf(stderr
, "Automatic merge went well; "
1270 "stopped before committing as requested\n");
1273 return suggest_conflicts();