4 * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
6 * Based on git-merge.sh by Junio C Hamano.
10 #include "parse-options.h"
12 #include "run-command.h"
18 #include "unpack-trees.h"
19 #include "cache-tree.h"
26 #include "merge-recursive.h"
27 #include "resolve-undo.h"
29 #define DEFAULT_TWOHEAD (1<<0)
30 #define DEFAULT_OCTOPUS (1<<1)
31 #define NO_FAST_FORWARD (1<<2)
32 #define NO_TRIVIAL (1<<3)
39 static const char * const builtin_merge_usage
[] = {
40 "git merge [options] <remote>...",
41 "git merge [options] <msg> HEAD <remote>",
45 static int show_diffstat
= 1, option_log
, squash
;
46 static int option_commit
= 1, allow_fast_forward
= 1;
47 static int fast_forward_only
;
48 static int allow_trivial
= 1, have_message
;
49 static struct strbuf merge_msg
;
50 static struct commit_list
*remoteheads
;
51 static unsigned char head
[20], stash
[20];
52 static struct strategy
**use_strategies
;
53 static size_t use_strategies_nr
, use_strategies_alloc
;
54 static const char **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
;
61 static struct strategy all_strategy
[] = {
62 { "recursive", DEFAULT_TWOHEAD
| NO_TRIVIAL
},
63 { "octopus", DEFAULT_OCTOPUS
},
65 { "ours", NO_FAST_FORWARD
| NO_TRIVIAL
},
66 { "subtree", NO_FAST_FORWARD
| NO_TRIVIAL
},
69 static const char *pull_twohead
, *pull_octopus
;
71 static int option_parse_message(const struct option
*opt
,
72 const char *arg
, int unset
)
74 struct strbuf
*buf
= opt
->value
;
77 strbuf_setlen(buf
, 0);
79 strbuf_addf(buf
, "%s%s", buf
->len
? "\n\n" : "", arg
);
82 return error("switch `m' requires a value");
86 static struct strategy
*get_strategy(const char *name
)
90 static struct cmdnames main_cmds
, other_cmds
;
96 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
97 if (!strcmp(name
, all_strategy
[i
].name
))
98 return &all_strategy
[i
];
101 struct cmdnames not_strategies
;
104 memset(¬_strategies
, 0, sizeof(struct cmdnames
));
105 load_command_list("git-merge-", &main_cmds
, &other_cmds
);
106 for (i
= 0; i
< main_cmds
.cnt
; i
++) {
108 struct cmdname
*ent
= main_cmds
.names
[i
];
109 for (j
= 0; j
< ARRAY_SIZE(all_strategy
); j
++)
110 if (!strncmp(ent
->name
, all_strategy
[j
].name
, ent
->len
)
111 && !all_strategy
[j
].name
[ent
->len
])
114 add_cmdname(¬_strategies
, ent
->name
, ent
->len
);
116 exclude_cmds(&main_cmds
, ¬_strategies
);
118 if (!is_in_cmdlist(&main_cmds
, name
) && !is_in_cmdlist(&other_cmds
, name
)) {
119 fprintf(stderr
, "Could not find merge strategy '%s'.\n", name
);
120 fprintf(stderr
, "Available strategies are:");
121 for (i
= 0; i
< main_cmds
.cnt
; i
++)
122 fprintf(stderr
, " %s", main_cmds
.names
[i
]->name
);
123 fprintf(stderr
, ".\n");
124 if (other_cmds
.cnt
) {
125 fprintf(stderr
, "Available custom strategies are:");
126 for (i
= 0; i
< other_cmds
.cnt
; i
++)
127 fprintf(stderr
, " %s", other_cmds
.names
[i
]->name
);
128 fprintf(stderr
, ".\n");
133 ret
= xcalloc(1, sizeof(struct strategy
));
134 ret
->name
= xstrdup(name
);
135 ret
->attr
= NO_TRIVIAL
;
139 static void append_strategy(struct strategy
*s
)
141 ALLOC_GROW(use_strategies
, use_strategies_nr
+ 1, use_strategies_alloc
);
142 use_strategies
[use_strategies_nr
++] = s
;
145 static int option_parse_strategy(const struct option
*opt
,
146 const char *name
, int unset
)
151 append_strategy(get_strategy(name
));
155 static int option_parse_x(const struct option
*opt
,
156 const char *arg
, int unset
)
161 ALLOC_GROW(xopts
, xopts_nr
+ 1, xopts_alloc
);
162 xopts
[xopts_nr
++] = xstrdup(arg
);
166 static int option_parse_n(const struct option
*opt
,
167 const char *arg
, int unset
)
169 show_diffstat
= unset
;
173 static struct option builtin_merge_options
[] = {
174 { OPTION_CALLBACK
, 'n', NULL
, NULL
, NULL
,
175 "do not show a diffstat at the end of the merge",
176 PARSE_OPT_NOARG
, option_parse_n
},
177 OPT_BOOLEAN(0, "stat", &show_diffstat
,
178 "show a diffstat at the end of the merge"),
179 OPT_BOOLEAN(0, "summary", &show_diffstat
, "(synonym to --stat)"),
180 OPT_BOOLEAN(0, "log", &option_log
,
181 "add list of one-line log to merge commit message"),
182 OPT_BOOLEAN(0, "squash", &squash
,
183 "create a single commit instead of doing a merge"),
184 OPT_BOOLEAN(0, "commit", &option_commit
,
185 "perform a commit if the merge succeeds (default)"),
186 OPT_BOOLEAN(0, "ff", &allow_fast_forward
,
187 "allow fast-forward (default)"),
188 OPT_BOOLEAN(0, "ff-only", &fast_forward_only
,
189 "abort if fast-forward is not possible"),
190 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto
),
191 OPT_CALLBACK('s', "strategy", &use_strategies
, "strategy",
192 "merge strategy to use", option_parse_strategy
),
193 OPT_CALLBACK('X', "strategy-option", &xopts
, "option=value",
194 "option for selected merge strategy", option_parse_x
),
195 OPT_CALLBACK('m', "message", &merge_msg
, "message",
196 "message to be used for the merge commit (if any)",
197 option_parse_message
),
198 OPT__VERBOSITY(&verbosity
),
202 /* Cleans up metadata that is uninteresting after a succeeded merge. */
203 static void drop_save(void)
205 unlink(git_path("MERGE_HEAD"));
206 unlink(git_path("MERGE_MSG"));
207 unlink(git_path("MERGE_MODE"));
210 static void save_state(void)
213 struct child_process cp
;
214 struct strbuf buffer
= STRBUF_INIT
;
215 const char *argv
[] = {"stash", "create", NULL
};
217 memset(&cp
, 0, sizeof(cp
));
222 if (start_command(&cp
))
223 die("could not run stash.");
224 len
= strbuf_read(&buffer
, cp
.out
, 1024);
227 if (finish_command(&cp
) || len
< 0)
231 strbuf_setlen(&buffer
, buffer
.len
-1);
232 if (get_sha1(buffer
.buf
, stash
))
233 die("not a valid object: %s", buffer
.buf
);
236 static void read_empty(unsigned const char *sha1
, int verbose
)
241 args
[i
++] = "read-tree";
246 args
[i
++] = EMPTY_TREE_SHA1_HEX
;
247 args
[i
++] = sha1_to_hex(sha1
);
250 if (run_command_v_opt(args
, RUN_GIT_CMD
))
251 die("read-tree failed");
254 static void reset_hard(unsigned const char *sha1
, int verbose
)
259 args
[i
++] = "read-tree";
262 args
[i
++] = "--reset";
264 args
[i
++] = sha1_to_hex(sha1
);
267 if (run_command_v_opt(args
, RUN_GIT_CMD
))
268 die("read-tree failed");
271 static void restore_state(void)
273 struct strbuf sb
= STRBUF_INIT
;
274 const char *args
[] = { "stash", "apply", NULL
, NULL
};
276 if (is_null_sha1(stash
))
281 args
[2] = sha1_to_hex(stash
);
284 * It is OK to ignore error here, for example when there was
285 * nothing to restore.
287 run_command_v_opt(args
, RUN_GIT_CMD
);
290 refresh_cache(REFRESH_QUIET
);
293 /* This is called when no merge was necessary. */
294 static void finish_up_to_date(const char *msg
)
297 printf("%s%s\n", squash
? " (nothing to squash)" : "", msg
);
301 static void squash_message(void)
304 struct commit
*commit
;
305 struct strbuf out
= STRBUF_INIT
;
306 struct commit_list
*j
;
308 struct pretty_print_context ctx
= {0};
310 printf("Squash commit -- not updating HEAD\n");
311 fd
= open(git_path("SQUASH_MSG"), O_WRONLY
| O_CREAT
, 0666);
313 die_errno("Could not write to '%s'", git_path("SQUASH_MSG"));
315 init_revisions(&rev
, NULL
);
316 rev
.ignore_merges
= 1;
317 rev
.commit_format
= CMIT_FMT_MEDIUM
;
319 commit
= lookup_commit(head
);
320 commit
->object
.flags
|= UNINTERESTING
;
321 add_pending_object(&rev
, &commit
->object
, NULL
);
323 for (j
= remoteheads
; j
; j
= j
->next
)
324 add_pending_object(&rev
, &j
->item
->object
, NULL
);
326 setup_revisions(0, NULL
, &rev
, NULL
);
327 if (prepare_revision_walk(&rev
))
328 die("revision walk setup failed");
330 ctx
.abbrev
= rev
.abbrev
;
331 ctx
.date_mode
= rev
.date_mode
;
333 strbuf_addstr(&out
, "Squashed commit of the following:\n");
334 while ((commit
= get_revision(&rev
)) != NULL
) {
335 strbuf_addch(&out
, '\n');
336 strbuf_addf(&out
, "commit %s\n",
337 sha1_to_hex(commit
->object
.sha1
));
338 pretty_print_commit(rev
.commit_format
, commit
, &out
, &ctx
);
340 if (write(fd
, out
.buf
, out
.len
) < 0)
341 die_errno("Writing SQUASH_MSG");
343 die_errno("Finishing SQUASH_MSG");
344 strbuf_release(&out
);
347 static void finish(const unsigned char *new_head
, const char *msg
)
349 struct strbuf reflog_message
= STRBUF_INIT
;
352 strbuf_addstr(&reflog_message
, getenv("GIT_REFLOG_ACTION"));
356 strbuf_addf(&reflog_message
, "%s: %s",
357 getenv("GIT_REFLOG_ACTION"), msg
);
362 if (verbosity
>= 0 && !merge_msg
.len
)
363 printf("No merge message -- not updating HEAD\n");
365 const char *argv_gc_auto
[] = { "gc", "--auto", NULL
};
366 update_ref(reflog_message
.buf
, "HEAD",
370 * We ignore errors in 'gc --auto', since the
371 * user should see them.
373 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
376 if (new_head
&& show_diffstat
) {
377 struct diff_options opts
;
379 opts
.output_format
|=
380 DIFF_FORMAT_SUMMARY
| DIFF_FORMAT_DIFFSTAT
;
381 opts
.detect_rename
= DIFF_DETECT_RENAME
;
382 if (diff_use_color_default
> 0)
383 DIFF_OPT_SET(&opts
, COLOR_DIFF
);
384 if (diff_setup_done(&opts
) < 0)
385 die("diff_setup_done failed");
386 diff_tree_sha1(head
, new_head
, "", &opts
);
391 /* Run a post-merge hook */
392 run_hook(NULL
, "post-merge", squash
? "1" : "0", NULL
);
394 strbuf_release(&reflog_message
);
397 /* Get the name for the merge commit's message. */
398 static void merge_name(const char *remote
, struct strbuf
*msg
)
400 struct object
*remote_head
;
401 unsigned char branch_head
[20], buf_sha
[20];
402 struct strbuf buf
= STRBUF_INIT
;
403 struct strbuf bname
= STRBUF_INIT
;
408 strbuf_branchname(&bname
, remote
);
411 memset(branch_head
, 0, sizeof(branch_head
));
412 remote_head
= peel_to_type(remote
, 0, NULL
, OBJ_COMMIT
);
414 die("'%s' does not point to a commit", remote
);
416 if (dwim_ref(remote
, strlen(remote
), branch_head
, &found_ref
) > 0) {
417 if (!prefixcmp(found_ref
, "refs/heads/")) {
418 strbuf_addf(msg
, "%s\t\tbranch '%s' of .\n",
419 sha1_to_hex(branch_head
), remote
);
422 if (!prefixcmp(found_ref
, "refs/remotes/")) {
423 strbuf_addf(msg
, "%s\t\tremote branch '%s' of .\n",
424 sha1_to_hex(branch_head
), remote
);
429 /* See if remote matches <name>^^^.. or <name>~<number> */
430 for (len
= 0, ptr
= remote
+ strlen(remote
);
431 remote
< ptr
&& ptr
[-1] == '^';
438 ptr
= strrchr(remote
, '~');
440 int seen_nonzero
= 0;
443 while (*++ptr
&& isdigit(*ptr
)) {
444 seen_nonzero
|= (*ptr
!= '0');
448 len
= 0; /* not ...~<number> */
449 else if (seen_nonzero
)
452 early
= 1; /* "name~" is "name~1"! */
456 struct strbuf truname
= STRBUF_INIT
;
457 strbuf_addstr(&truname
, "refs/heads/");
458 strbuf_addstr(&truname
, remote
);
459 strbuf_setlen(&truname
, truname
.len
- len
);
460 if (resolve_ref(truname
.buf
, buf_sha
, 1, NULL
)) {
462 "%s\t\tbranch '%s'%s of .\n",
463 sha1_to_hex(remote_head
->sha1
),
465 (early
? " (early part)" : ""));
466 strbuf_release(&truname
);
471 if (!strcmp(remote
, "FETCH_HEAD") &&
472 !access(git_path("FETCH_HEAD"), R_OK
)) {
474 struct strbuf line
= STRBUF_INIT
;
477 fp
= fopen(git_path("FETCH_HEAD"), "r");
479 die_errno("could not open '%s' for reading",
480 git_path("FETCH_HEAD"));
481 strbuf_getline(&line
, fp
, '\n');
483 ptr
= strstr(line
.buf
, "\tnot-for-merge\t");
485 strbuf_remove(&line
, ptr
-line
.buf
+1, 13);
486 strbuf_addbuf(msg
, &line
);
487 strbuf_release(&line
);
490 strbuf_addf(msg
, "%s\t\tcommit '%s'\n",
491 sha1_to_hex(remote_head
->sha1
), remote
);
493 strbuf_release(&buf
);
494 strbuf_release(&bname
);
497 static int git_merge_config(const char *k
, const char *v
, void *cb
)
499 if (branch
&& !prefixcmp(k
, "branch.") &&
500 !prefixcmp(k
+ 7, branch
) &&
501 !strcmp(k
+ 7 + strlen(branch
), ".mergeoptions")) {
507 argc
= split_cmdline(buf
, &argv
);
509 die("Bad branch.%s.mergeoptions string: %s", branch
,
510 split_cmdline_strerror(argc
));
511 argv
= xrealloc(argv
, sizeof(*argv
) * (argc
+ 2));
512 memmove(argv
+ 1, argv
, sizeof(*argv
) * (argc
+ 1));
514 parse_options(argc
, argv
, NULL
, builtin_merge_options
,
515 builtin_merge_usage
, 0);
519 if (!strcmp(k
, "merge.diffstat") || !strcmp(k
, "merge.stat"))
520 show_diffstat
= git_config_bool(k
, v
);
521 else if (!strcmp(k
, "pull.twohead"))
522 return git_config_string(&pull_twohead
, k
, v
);
523 else if (!strcmp(k
, "pull.octopus"))
524 return git_config_string(&pull_octopus
, k
, v
);
525 else if (!strcmp(k
, "merge.log") || !strcmp(k
, "merge.summary"))
526 option_log
= git_config_bool(k
, v
);
527 else if (!strcmp(k
, "merge.renormalize"))
528 option_renormalize
= git_config_bool(k
, v
);
529 return git_diff_ui_config(k
, v
, cb
);
532 static int read_tree_trivial(unsigned char *common
, unsigned char *head
,
536 struct tree
*trees
[MAX_UNPACK_TREES
];
537 struct tree_desc t
[MAX_UNPACK_TREES
];
538 struct unpack_trees_options opts
;
540 memset(&opts
, 0, sizeof(opts
));
542 opts
.src_index
= &the_index
;
543 opts
.dst_index
= &the_index
;
545 opts
.verbose_update
= 1;
546 opts
.trivial_merges_only
= 1;
548 trees
[nr_trees
] = parse_tree_indirect(common
);
549 if (!trees
[nr_trees
++])
551 trees
[nr_trees
] = parse_tree_indirect(head
);
552 if (!trees
[nr_trees
++])
554 trees
[nr_trees
] = parse_tree_indirect(one
);
555 if (!trees
[nr_trees
++])
557 opts
.fn
= threeway_merge
;
558 cache_tree_free(&active_cache_tree
);
559 for (i
= 0; i
< nr_trees
; i
++) {
560 parse_tree(trees
[i
]);
561 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
563 if (unpack_trees(nr_trees
, t
, &opts
))
568 static void write_tree_trivial(unsigned char *sha1
)
570 if (write_cache_as_tree(sha1
, 0, NULL
))
571 die("git write-tree failed to write a tree");
574 int try_merge_command(const char *strategy
, struct commit_list
*common
,
575 const char *head_arg
, struct commit_list
*remotes
)
578 int i
= 0, x
= 0, ret
;
579 struct commit_list
*j
;
580 struct strbuf buf
= STRBUF_INIT
;
582 args
= xmalloc((4 + xopts_nr
+ commit_list_count(common
) +
583 commit_list_count(remotes
)) * sizeof(char *));
584 strbuf_addf(&buf
, "merge-%s", strategy
);
586 for (x
= 0; x
< xopts_nr
; x
++) {
587 char *s
= xmalloc(strlen(xopts
[x
])+2+1);
589 strcpy(s
+2, xopts
[x
]);
592 for (j
= common
; j
; j
= j
->next
)
593 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
595 args
[i
++] = head_arg
;
596 for (j
= remotes
; j
; j
= j
->next
)
597 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
599 ret
= run_command_v_opt(args
, RUN_GIT_CMD
);
600 strbuf_release(&buf
);
602 for (x
= 0; x
< xopts_nr
; x
++)
603 free((void *)args
[i
++]);
604 for (j
= common
; j
; j
= j
->next
)
605 free((void *)args
[i
++]);
607 for (j
= remotes
; j
; j
= j
->next
)
608 free((void *)args
[i
++]);
611 if (read_cache() < 0)
612 die("failed to read the cache");
613 resolve_undo_clear();
618 static int try_merge_strategy(const char *strategy
, struct commit_list
*common
,
619 const char *head_arg
)
622 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
624 index_fd
= hold_locked_index(lock
, 1);
625 refresh_cache(REFRESH_QUIET
);
626 if (active_cache_changed
&&
627 (write_cache(index_fd
, active_cache
, active_nr
) ||
628 commit_locked_index(lock
)))
629 return error("Unable to write index.");
630 rollback_lock_file(lock
);
632 if (!strcmp(strategy
, "recursive") || !strcmp(strategy
, "subtree")) {
634 struct commit
*result
;
635 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
637 struct commit_list
*reversed
= NULL
;
638 struct merge_options o
;
639 struct commit_list
*j
;
641 if (remoteheads
->next
) {
642 error("Not handling anything other than two heads merge.");
646 init_merge_options(&o
);
647 if (!strcmp(strategy
, "subtree"))
648 o
.subtree_shift
= "";
650 o
.renormalize
= option_renormalize
;
653 * NEEDSWORK: merge with table in builtin/merge-recursive
655 for (x
= 0; x
< xopts_nr
; x
++) {
656 if (!strcmp(xopts
[x
], "ours"))
657 o
.recursive_variant
= MERGE_RECURSIVE_OURS
;
658 else if (!strcmp(xopts
[x
], "theirs"))
659 o
.recursive_variant
= MERGE_RECURSIVE_THEIRS
;
660 else if (!strcmp(xopts
[x
], "subtree"))
661 o
.subtree_shift
= "";
662 else if (!prefixcmp(xopts
[x
], "subtree="))
663 o
.subtree_shift
= xopts
[x
]+8;
664 else if (!strcmp(xopts
[x
], "renormalize"))
666 else if (!strcmp(xopts
[x
], "no-renormalize"))
669 die("Unknown option for merge-recursive: -X%s", xopts
[x
]);
672 o
.branch1
= head_arg
;
673 o
.branch2
= remoteheads
->item
->util
;
675 for (j
= common
; j
; j
= j
->next
)
676 commit_list_insert(j
->item
, &reversed
);
678 index_fd
= hold_locked_index(lock
, 1);
679 clean
= merge_recursive(&o
, lookup_commit(head
),
680 remoteheads
->item
, reversed
, &result
);
681 if (active_cache_changed
&&
682 (write_cache(index_fd
, active_cache
, active_nr
) ||
683 commit_locked_index(lock
)))
684 die ("unable to write %s", get_index_file());
685 rollback_lock_file(lock
);
686 return clean
? 0 : 1;
688 return try_merge_command(strategy
, common
, head_arg
, remoteheads
);
692 static void count_diff_files(struct diff_queue_struct
*q
,
693 struct diff_options
*opt
, void *data
)
700 static int count_unmerged_entries(void)
704 for (i
= 0; i
< active_nr
; i
++)
705 if (ce_stage(active_cache
[i
]))
711 int checkout_fast_forward(const unsigned char *head
, const unsigned char *remote
)
713 struct tree
*trees
[MAX_UNPACK_TREES
];
714 struct unpack_trees_options opts
;
715 struct tree_desc t
[MAX_UNPACK_TREES
];
716 int i
, fd
, nr_trees
= 0;
717 struct dir_struct dir
;
718 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
720 refresh_cache(REFRESH_QUIET
);
722 fd
= hold_locked_index(lock_file
, 1);
724 memset(&trees
, 0, sizeof(trees
));
725 memset(&opts
, 0, sizeof(opts
));
726 memset(&t
, 0, sizeof(t
));
727 memset(&dir
, 0, sizeof(dir
));
728 dir
.flags
|= DIR_SHOW_IGNORED
;
729 dir
.exclude_per_dir
= ".gitignore";
733 opts
.src_index
= &the_index
;
734 opts
.dst_index
= &the_index
;
736 opts
.verbose_update
= 1;
738 opts
.fn
= twoway_merge
;
739 setup_unpack_trees_porcelain(&opts
, "merge");
741 trees
[nr_trees
] = parse_tree_indirect(head
);
742 if (!trees
[nr_trees
++])
744 trees
[nr_trees
] = parse_tree_indirect(remote
);
745 if (!trees
[nr_trees
++])
747 for (i
= 0; i
< nr_trees
; i
++) {
748 parse_tree(trees
[i
]);
749 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
751 if (unpack_trees(nr_trees
, t
, &opts
))
753 if (write_cache(fd
, active_cache
, active_nr
) ||
754 commit_locked_index(lock_file
))
755 die("unable to write new index file");
759 static void split_merge_strategies(const char *string
, struct strategy
**list
,
767 buf
= xstrdup(string
);
772 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
773 (*list
)[(*nr
)++].name
= xstrdup(q
);
778 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
779 (*list
)[(*nr
)++].name
= xstrdup(q
);
785 static void add_strategies(const char *string
, unsigned attr
)
787 struct strategy
*list
= NULL
;
788 int list_alloc
= 0, list_nr
= 0, i
;
790 memset(&list
, 0, sizeof(list
));
791 split_merge_strategies(string
, &list
, &list_nr
, &list_alloc
);
793 for (i
= 0; i
< list_nr
; i
++)
794 append_strategy(get_strategy(list
[i
].name
));
797 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
798 if (all_strategy
[i
].attr
& attr
)
799 append_strategy(&all_strategy
[i
]);
803 static int merge_trivial(void)
805 unsigned char result_tree
[20], result_commit
[20];
806 struct commit_list
*parent
= xmalloc(sizeof(*parent
));
808 write_tree_trivial(result_tree
);
809 printf("Wonderful.\n");
810 parent
->item
= lookup_commit(head
);
811 parent
->next
= xmalloc(sizeof(*parent
->next
));
812 parent
->next
->item
= remoteheads
->item
;
813 parent
->next
->next
= NULL
;
814 commit_tree(merge_msg
.buf
, result_tree
, parent
, result_commit
, NULL
);
815 finish(result_commit
, "In-index merge");
820 static int finish_automerge(struct commit_list
*common
,
821 unsigned char *result_tree
,
822 const char *wt_strategy
)
824 struct commit_list
*parents
= NULL
, *j
;
825 struct strbuf buf
= STRBUF_INIT
;
826 unsigned char result_commit
[20];
828 free_commit_list(common
);
829 if (allow_fast_forward
) {
830 parents
= remoteheads
;
831 commit_list_insert(lookup_commit(head
), &parents
);
832 parents
= reduce_heads(parents
);
834 struct commit_list
**pptr
= &parents
;
836 pptr
= &commit_list_insert(lookup_commit(head
),
838 for (j
= remoteheads
; j
; j
= j
->next
)
839 pptr
= &commit_list_insert(j
->item
, pptr
)->next
;
841 free_commit_list(remoteheads
);
842 strbuf_addch(&merge_msg
, '\n');
843 commit_tree(merge_msg
.buf
, result_tree
, parents
, result_commit
, NULL
);
844 strbuf_addf(&buf
, "Merge made by %s.", wt_strategy
);
845 finish(result_commit
, buf
.buf
);
846 strbuf_release(&buf
);
851 static int suggest_conflicts(int renormalizing
)
856 fp
= fopen(git_path("MERGE_MSG"), "a");
858 die_errno("Could not open '%s' for writing",
859 git_path("MERGE_MSG"));
860 fprintf(fp
, "\nConflicts:\n");
861 for (pos
= 0; pos
< active_nr
; pos
++) {
862 struct cache_entry
*ce
= active_cache
[pos
];
865 fprintf(fp
, "\t%s\n", ce
->name
);
866 while (pos
+ 1 < active_nr
&&
868 active_cache
[pos
+ 1]->name
))
873 rerere(allow_rerere_auto
);
874 printf("Automatic merge failed; "
875 "fix conflicts and then commit the result.\n");
879 static struct commit
*is_old_style_invocation(int argc
, const char **argv
)
881 struct commit
*second_token
= NULL
;
883 unsigned char second_sha1
[20];
885 if (get_sha1(argv
[1], second_sha1
))
887 second_token
= lookup_commit_reference_gently(second_sha1
, 0);
889 die("'%s' is not a commit", argv
[1]);
890 if (hashcmp(second_token
->object
.sha1
, head
))
896 static int evaluate_result(void)
901 /* Check how many files differ. */
902 init_revisions(&rev
, "");
903 setup_revisions(0, NULL
, &rev
, NULL
);
904 rev
.diffopt
.output_format
|=
905 DIFF_FORMAT_CALLBACK
;
906 rev
.diffopt
.format_callback
= count_diff_files
;
907 rev
.diffopt
.format_callback_data
= &cnt
;
908 run_diff_files(&rev
, 0);
911 * Check how many unmerged entries are
914 cnt
+= count_unmerged_entries();
919 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
921 unsigned char result_tree
[20];
922 struct strbuf buf
= STRBUF_INIT
;
923 const char *head_arg
;
924 int flag
, head_invalid
= 0, i
;
925 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
926 struct commit_list
*common
= NULL
;
927 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
928 struct commit_list
**remotes
= &remoteheads
;
930 if (read_cache_unmerged()) {
931 die_resolve_conflict("merge");
933 if (file_exists(git_path("MERGE_HEAD"))) {
935 * There is no unmerged entry, don't advise 'git
936 * add/rm <file>', just 'git commit'.
938 if (advice_resolve_conflict
)
939 die("You have not concluded your merge (MERGE_HEAD exists).\n"
940 "Please, commit your changes before you can merge.");
942 die("You have not concluded your merge (MERGE_HEAD exists).");
945 resolve_undo_clear();
947 * Check if we are _not_ on a detached HEAD, i.e. if there is a
950 branch
= resolve_ref("HEAD", head
, 0, &flag
);
951 if (branch
&& !prefixcmp(branch
, "refs/heads/"))
953 if (is_null_sha1(head
))
956 git_config(git_merge_config
, NULL
);
959 if (diff_use_color_default
== -1)
960 diff_use_color_default
= git_use_color_default
;
962 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
963 builtin_merge_usage
, 0);
968 if (!allow_fast_forward
)
969 die("You cannot combine --squash with --no-ff.");
973 if (!allow_fast_forward
&& fast_forward_only
)
974 die("You cannot combine --no-ff with --ff-only.");
977 usage_with_options(builtin_merge_usage
,
978 builtin_merge_options
);
981 * This could be traditional "merge <msg> HEAD <commit>..." and
982 * the way we can tell it is to see if the second token is HEAD,
983 * but some people might have misused the interface and used a
984 * committish that is the same as HEAD there instead.
985 * Traditional format never would have "-m" so it is an
986 * additional safety measure to check for it.
989 if (!have_message
&& is_old_style_invocation(argc
, argv
)) {
990 strbuf_addstr(&merge_msg
, argv
[0]);
994 } else if (head_invalid
) {
995 struct object
*remote_head
;
997 * If the merged head is a valid one there is no reason
998 * to forbid "git merge" into a branch yet to be born.
999 * We do the same for "git pull".
1002 die("Can merge only exactly one commit into "
1005 die("Squash commit into empty head not supported yet");
1006 if (!allow_fast_forward
)
1007 die("Non-fast-forward commit does not make sense into "
1009 remote_head
= peel_to_type(argv
[0], 0, NULL
, OBJ_COMMIT
);
1011 die("%s - not something we can merge", argv
[0]);
1012 update_ref("initial pull", "HEAD", remote_head
->sha1
, NULL
, 0,
1014 read_empty(remote_head
->sha1
, 0);
1017 struct strbuf merge_names
= STRBUF_INIT
;
1019 /* We are invoked directly as the first-class UI. */
1023 * All the rest are the commits being merged;
1024 * prepare the standard merge summary message to
1025 * be appended to the given message. If remote
1026 * is invalid we will die later in the common
1027 * codepath so we discard the error in this
1030 for (i
= 0; i
< argc
; i
++)
1031 merge_name(argv
[i
], &merge_names
);
1033 if (have_message
&& option_log
)
1034 fmt_merge_msg_shortlog(&merge_names
, &merge_msg
);
1035 else if (!have_message
)
1036 fmt_merge_msg(option_log
, &merge_names
, &merge_msg
);
1039 if (!(have_message
&& !option_log
) && merge_msg
.len
)
1040 strbuf_setlen(&merge_msg
, merge_msg
.len
-1);
1043 if (head_invalid
|| !argc
)
1044 usage_with_options(builtin_merge_usage
,
1045 builtin_merge_options
);
1047 strbuf_addstr(&buf
, "merge");
1048 for (i
= 0; i
< argc
; i
++)
1049 strbuf_addf(&buf
, " %s", argv
[i
]);
1050 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
1053 for (i
= 0; i
< argc
; i
++) {
1055 struct commit
*commit
;
1057 o
= peel_to_type(argv
[i
], 0, NULL
, OBJ_COMMIT
);
1059 die("%s - not something we can merge", argv
[i
]);
1060 commit
= lookup_commit(o
->sha1
);
1061 commit
->util
= (void *)argv
[i
];
1062 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1064 strbuf_addf(&buf
, "GITHEAD_%s", sha1_to_hex(o
->sha1
));
1065 setenv(buf
.buf
, argv
[i
], 1);
1069 if (!use_strategies
) {
1070 if (!remoteheads
->next
)
1071 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
1073 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
1076 for (i
= 0; i
< use_strategies_nr
; i
++) {
1077 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
1078 allow_fast_forward
= 0;
1079 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
1083 if (!remoteheads
->next
)
1084 common
= get_merge_bases(lookup_commit(head
),
1085 remoteheads
->item
, 1);
1087 struct commit_list
*list
= remoteheads
;
1088 commit_list_insert(lookup_commit(head
), &list
);
1089 common
= get_octopus_merge_bases(list
);
1093 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head
, NULL
, 0,
1097 ; /* No common ancestors found. We need a real merge. */
1098 else if (!remoteheads
->next
&& !common
->next
&&
1099 common
->item
== remoteheads
->item
) {
1101 * If head can reach all the merge then we are up to date.
1102 * but first the most common case of merging one remote.
1104 finish_up_to_date("Already up-to-date.");
1106 } else if (allow_fast_forward
&& !remoteheads
->next
&&
1108 !hashcmp(common
->item
->object
.sha1
, head
)) {
1109 /* Again the most common case of merging one remote. */
1110 struct strbuf msg
= STRBUF_INIT
;
1114 strcpy(hex
, find_unique_abbrev(head
, DEFAULT_ABBREV
));
1117 printf("Updating %s..%s\n",
1119 find_unique_abbrev(remoteheads
->item
->object
.sha1
,
1121 strbuf_addstr(&msg
, "Fast-forward");
1124 " (no commit created; -m option ignored)");
1125 o
= peel_to_type(sha1_to_hex(remoteheads
->item
->object
.sha1
),
1126 0, NULL
, OBJ_COMMIT
);
1130 if (checkout_fast_forward(head
, remoteheads
->item
->object
.sha1
))
1133 finish(o
->sha1
, msg
.buf
);
1136 } else if (!remoteheads
->next
&& common
->next
)
1139 * We are not doing octopus and not fast-forward. Need
1142 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1144 * We are not doing octopus, not fast-forward, and have
1147 refresh_cache(REFRESH_QUIET
);
1148 if (allow_trivial
&& !fast_forward_only
) {
1149 /* See if it is really trivial. */
1150 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1151 printf("Trying really trivial in-index merge...\n");
1152 if (!read_tree_trivial(common
->item
->object
.sha1
,
1153 head
, remoteheads
->item
->object
.sha1
))
1154 return merge_trivial();
1159 * An octopus. If we can reach all the remote we are up
1163 struct commit_list
*j
;
1165 for (j
= remoteheads
; j
; j
= j
->next
) {
1166 struct commit_list
*common_one
;
1169 * Here we *have* to calculate the individual
1170 * merge_bases again, otherwise "git merge HEAD^
1171 * HEAD^^" would be missed.
1173 common_one
= get_merge_bases(lookup_commit(head
),
1175 if (hashcmp(common_one
->item
->object
.sha1
,
1176 j
->item
->object
.sha1
)) {
1182 finish_up_to_date("Already up-to-date. Yeeah!");
1187 if (fast_forward_only
)
1188 die("Not possible to fast-forward, aborting.");
1190 /* We are going to make a new commit. */
1191 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1194 * At this point, we need a real merge. No matter what strategy
1195 * we use, it would operate on the index, possibly affecting the
1196 * working tree, and when resolved cleanly, have the desired
1197 * tree in the index -- this means that the index must be in
1198 * sync with the head commit. The strategies are responsible
1201 if (use_strategies_nr
!= 1) {
1203 * Stash away the local changes so that we can try more
1208 memcpy(stash
, null_sha1
, 20);
1211 for (i
= 0; i
< use_strategies_nr
; i
++) {
1214 printf("Rewinding the tree to pristine...\n");
1217 if (use_strategies_nr
!= 1)
1218 printf("Trying merge strategy %s...\n",
1219 use_strategies
[i
]->name
);
1221 * Remember which strategy left the state in the working
1224 wt_strategy
= use_strategies
[i
]->name
;
1226 ret
= try_merge_strategy(use_strategies
[i
]->name
,
1228 if (!option_commit
&& !ret
) {
1231 * This is necessary here just to avoid writing
1232 * the tree, but later we will *not* exit with
1233 * status code 1 because merge_was_ok is set.
1240 * The backend exits with 1 when conflicts are
1241 * left to be resolved, with 2 when it does not
1242 * handle the given merge at all.
1245 int cnt
= evaluate_result();
1247 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1248 best_strategy
= use_strategies
[i
]->name
;
1258 /* Automerge succeeded. */
1259 write_tree_trivial(result_tree
);
1260 automerge_was_ok
= 1;
1265 * If we have a resulting tree, that means the strategy module
1266 * auto resolved the merge cleanly.
1268 if (automerge_was_ok
)
1269 return finish_automerge(common
, result_tree
, wt_strategy
);
1272 * Pick the result from the best strategy and have the user fix
1275 if (!best_strategy
) {
1277 if (use_strategies_nr
> 1)
1279 "No merge strategy handled the merge.\n");
1281 fprintf(stderr
, "Merge with strategy %s failed.\n",
1282 use_strategies
[0]->name
);
1284 } else if (best_strategy
== wt_strategy
)
1285 ; /* We already have its result in the working tree. */
1287 printf("Rewinding the tree to pristine...\n");
1289 printf("Using the %s to prepare resolving by hand.\n",
1291 try_merge_strategy(best_strategy
, common
, head_arg
);
1298 struct commit_list
*j
;
1300 for (j
= remoteheads
; j
; j
= j
->next
)
1301 strbuf_addf(&buf
, "%s\n",
1302 sha1_to_hex(j
->item
->object
.sha1
));
1303 fd
= open(git_path("MERGE_HEAD"), O_WRONLY
| O_CREAT
, 0666);
1305 die_errno("Could not open '%s' for writing",
1306 git_path("MERGE_HEAD"));
1307 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1308 die_errno("Could not write to '%s'", git_path("MERGE_HEAD"));
1310 strbuf_addch(&merge_msg
, '\n');
1311 fd
= open(git_path("MERGE_MSG"), O_WRONLY
| O_CREAT
, 0666);
1313 die_errno("Could not open '%s' for writing",
1314 git_path("MERGE_MSG"));
1315 if (write_in_full(fd
, merge_msg
.buf
, merge_msg
.len
) !=
1317 die_errno("Could not write to '%s'", git_path("MERGE_MSG"));
1319 fd
= open(git_path("MERGE_MODE"), O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
1321 die_errno("Could not open '%s' for writing",
1322 git_path("MERGE_MODE"));
1324 if (!allow_fast_forward
)
1325 strbuf_addf(&buf
, "no-ff");
1326 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1327 die_errno("Could not write to '%s'", git_path("MERGE_MODE"));
1332 fprintf(stderr
, "Automatic merge went well; "
1333 "stopped before committing as requested\n");
1336 return suggest_conflicts(option_renormalize
);