4 * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
6 * Based on git-merge.sh by Junio C Hamano.
10 #include "parse-options.h"
12 #include "run-command.h"
18 #include "unpack-trees.h"
19 #include "cache-tree.h"
26 #include "merge-recursive.h"
27 #include "resolve-undo.h"
29 #define DEFAULT_TWOHEAD (1<<0)
30 #define DEFAULT_OCTOPUS (1<<1)
31 #define NO_FAST_FORWARD (1<<2)
32 #define NO_TRIVIAL (1<<3)
39 static const char * const builtin_merge_usage
[] = {
40 "git merge [options] <remote>...",
41 "git merge [options] <msg> HEAD <remote>",
45 static int show_diffstat
= 1, shortlog_len
, squash
;
46 static int option_commit
= 1, allow_fast_forward
= 1;
47 static int fast_forward_only
;
48 static int allow_trivial
= 1, have_message
;
49 static struct strbuf merge_msg
;
50 static struct commit_list
*remoteheads
;
51 static unsigned char head
[20], stash
[20];
52 static struct strategy
**use_strategies
;
53 static size_t use_strategies_nr
, use_strategies_alloc
;
54 static const char **xopts
;
55 static size_t xopts_nr
, xopts_alloc
;
56 static const char *branch
;
57 static int option_renormalize
;
59 static int allow_rerere_auto
;
60 static int abort_current_merge
;
62 static struct strategy all_strategy
[] = {
63 { "recursive", DEFAULT_TWOHEAD
| NO_TRIVIAL
},
64 { "octopus", DEFAULT_OCTOPUS
},
66 { "ours", NO_FAST_FORWARD
| NO_TRIVIAL
},
67 { "subtree", NO_FAST_FORWARD
| NO_TRIVIAL
},
70 static const char *pull_twohead
, *pull_octopus
;
72 static int option_parse_message(const struct option
*opt
,
73 const char *arg
, int unset
)
75 struct strbuf
*buf
= opt
->value
;
78 strbuf_setlen(buf
, 0);
80 strbuf_addf(buf
, "%s%s", buf
->len
? "\n\n" : "", arg
);
83 return error("switch `m' requires a value");
87 static struct strategy
*get_strategy(const char *name
)
91 static struct cmdnames main_cmds
, other_cmds
;
97 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
98 if (!strcmp(name
, all_strategy
[i
].name
))
99 return &all_strategy
[i
];
102 struct cmdnames not_strategies
;
105 memset(¬_strategies
, 0, sizeof(struct cmdnames
));
106 load_command_list("git-merge-", &main_cmds
, &other_cmds
);
107 for (i
= 0; i
< main_cmds
.cnt
; i
++) {
109 struct cmdname
*ent
= main_cmds
.names
[i
];
110 for (j
= 0; j
< ARRAY_SIZE(all_strategy
); j
++)
111 if (!strncmp(ent
->name
, all_strategy
[j
].name
, ent
->len
)
112 && !all_strategy
[j
].name
[ent
->len
])
115 add_cmdname(¬_strategies
, ent
->name
, ent
->len
);
117 exclude_cmds(&main_cmds
, ¬_strategies
);
119 if (!is_in_cmdlist(&main_cmds
, name
) && !is_in_cmdlist(&other_cmds
, name
)) {
120 fprintf(stderr
, "Could not find merge strategy '%s'.\n", name
);
121 fprintf(stderr
, "Available strategies are:");
122 for (i
= 0; i
< main_cmds
.cnt
; i
++)
123 fprintf(stderr
, " %s", main_cmds
.names
[i
]->name
);
124 fprintf(stderr
, ".\n");
125 if (other_cmds
.cnt
) {
126 fprintf(stderr
, "Available custom strategies are:");
127 for (i
= 0; i
< other_cmds
.cnt
; i
++)
128 fprintf(stderr
, " %s", other_cmds
.names
[i
]->name
);
129 fprintf(stderr
, ".\n");
134 ret
= xcalloc(1, sizeof(struct strategy
));
135 ret
->name
= xstrdup(name
);
136 ret
->attr
= NO_TRIVIAL
;
140 static void append_strategy(struct strategy
*s
)
142 ALLOC_GROW(use_strategies
, use_strategies_nr
+ 1, use_strategies_alloc
);
143 use_strategies
[use_strategies_nr
++] = s
;
146 static int option_parse_strategy(const struct option
*opt
,
147 const char *name
, int unset
)
152 append_strategy(get_strategy(name
));
156 static int option_parse_x(const struct option
*opt
,
157 const char *arg
, int unset
)
162 ALLOC_GROW(xopts
, xopts_nr
+ 1, xopts_alloc
);
163 xopts
[xopts_nr
++] = xstrdup(arg
);
167 static int option_parse_n(const struct option
*opt
,
168 const char *arg
, int unset
)
170 show_diffstat
= unset
;
174 static struct option builtin_merge_options
[] = {
175 { OPTION_CALLBACK
, 'n', NULL
, NULL
, NULL
,
176 "do not show a diffstat at the end of the merge",
177 PARSE_OPT_NOARG
, option_parse_n
},
178 OPT_BOOLEAN(0, "stat", &show_diffstat
,
179 "show a diffstat at the end of the merge"),
180 OPT_BOOLEAN(0, "summary", &show_diffstat
, "(synonym to --stat)"),
181 { OPTION_INTEGER
, 0, "log", &shortlog_len
, "n",
182 "add (at most <n>) entries from shortlog to merge commit message",
183 PARSE_OPT_OPTARG
, NULL
, DEFAULT_MERGE_LOG_LEN
},
184 OPT_BOOLEAN(0, "squash", &squash
,
185 "create a single commit instead of doing a merge"),
186 OPT_BOOLEAN(0, "commit", &option_commit
,
187 "perform a commit if the merge succeeds (default)"),
188 OPT_BOOLEAN(0, "ff", &allow_fast_forward
,
189 "allow fast-forward (default)"),
190 OPT_BOOLEAN(0, "ff-only", &fast_forward_only
,
191 "abort if fast-forward is not possible"),
192 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto
),
193 OPT_CALLBACK('s', "strategy", &use_strategies
, "strategy",
194 "merge strategy to use", option_parse_strategy
),
195 OPT_CALLBACK('X', "strategy-option", &xopts
, "option=value",
196 "option for selected merge strategy", option_parse_x
),
197 OPT_CALLBACK('m', "message", &merge_msg
, "MESSAGE",
198 "merge commit message (for a non-fast-forward merge)",
199 option_parse_message
),
200 OPT__VERBOSITY(&verbosity
),
201 OPT_BOOLEAN(0, "abort", &abort_current_merge
,
202 "abort the current in-progress merge"),
206 /* Cleans up metadata that is uninteresting after a succeeded merge. */
207 static void drop_save(void)
209 unlink(git_path("MERGE_HEAD"));
210 unlink(git_path("MERGE_MSG"));
211 unlink(git_path("MERGE_MODE"));
214 static void save_state(void)
217 struct child_process cp
;
218 struct strbuf buffer
= STRBUF_INIT
;
219 const char *argv
[] = {"stash", "create", NULL
};
221 memset(&cp
, 0, sizeof(cp
));
226 if (start_command(&cp
))
227 die("could not run stash.");
228 len
= strbuf_read(&buffer
, cp
.out
, 1024);
231 if (finish_command(&cp
) || len
< 0)
235 strbuf_setlen(&buffer
, buffer
.len
-1);
236 if (get_sha1(buffer
.buf
, stash
))
237 die("not a valid object: %s", buffer
.buf
);
240 static void read_empty(unsigned const char *sha1
, int verbose
)
245 args
[i
++] = "read-tree";
250 args
[i
++] = EMPTY_TREE_SHA1_HEX
;
251 args
[i
++] = sha1_to_hex(sha1
);
254 if (run_command_v_opt(args
, RUN_GIT_CMD
))
255 die("read-tree failed");
258 static void reset_hard(unsigned const char *sha1
, int verbose
)
263 args
[i
++] = "read-tree";
266 args
[i
++] = "--reset";
268 args
[i
++] = sha1_to_hex(sha1
);
271 if (run_command_v_opt(args
, RUN_GIT_CMD
))
272 die("read-tree failed");
275 static void restore_state(void)
277 struct strbuf sb
= STRBUF_INIT
;
278 const char *args
[] = { "stash", "apply", NULL
, NULL
};
280 if (is_null_sha1(stash
))
285 args
[2] = sha1_to_hex(stash
);
288 * It is OK to ignore error here, for example when there was
289 * nothing to restore.
291 run_command_v_opt(args
, RUN_GIT_CMD
);
294 refresh_cache(REFRESH_QUIET
);
297 /* This is called when no merge was necessary. */
298 static void finish_up_to_date(const char *msg
)
301 printf("%s%s\n", squash
? " (nothing to squash)" : "", msg
);
305 static void squash_message(void)
308 struct commit
*commit
;
309 struct strbuf out
= STRBUF_INIT
;
310 struct commit_list
*j
;
312 struct pretty_print_context ctx
= {0};
314 printf("Squash commit -- not updating HEAD\n");
315 fd
= open(git_path("SQUASH_MSG"), O_WRONLY
| O_CREAT
, 0666);
317 die_errno("Could not write to '%s'", git_path("SQUASH_MSG"));
319 init_revisions(&rev
, NULL
);
320 rev
.ignore_merges
= 1;
321 rev
.commit_format
= CMIT_FMT_MEDIUM
;
323 commit
= lookup_commit(head
);
324 commit
->object
.flags
|= UNINTERESTING
;
325 add_pending_object(&rev
, &commit
->object
, NULL
);
327 for (j
= remoteheads
; j
; j
= j
->next
)
328 add_pending_object(&rev
, &j
->item
->object
, NULL
);
330 setup_revisions(0, NULL
, &rev
, NULL
);
331 if (prepare_revision_walk(&rev
))
332 die("revision walk setup failed");
334 ctx
.abbrev
= rev
.abbrev
;
335 ctx
.date_mode
= rev
.date_mode
;
337 strbuf_addstr(&out
, "Squashed commit of the following:\n");
338 while ((commit
= get_revision(&rev
)) != NULL
) {
339 strbuf_addch(&out
, '\n');
340 strbuf_addf(&out
, "commit %s\n",
341 sha1_to_hex(commit
->object
.sha1
));
342 pretty_print_commit(rev
.commit_format
, commit
, &out
, &ctx
);
344 if (write(fd
, out
.buf
, out
.len
) < 0)
345 die_errno("Writing SQUASH_MSG");
347 die_errno("Finishing SQUASH_MSG");
348 strbuf_release(&out
);
351 static void finish(const unsigned char *new_head
, const char *msg
)
353 struct strbuf reflog_message
= STRBUF_INIT
;
356 strbuf_addstr(&reflog_message
, getenv("GIT_REFLOG_ACTION"));
360 strbuf_addf(&reflog_message
, "%s: %s",
361 getenv("GIT_REFLOG_ACTION"), msg
);
366 if (verbosity
>= 0 && !merge_msg
.len
)
367 printf("No merge message -- not updating HEAD\n");
369 const char *argv_gc_auto
[] = { "gc", "--auto", NULL
};
370 update_ref(reflog_message
.buf
, "HEAD",
374 * We ignore errors in 'gc --auto', since the
375 * user should see them.
377 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
380 if (new_head
&& show_diffstat
) {
381 struct diff_options opts
;
383 opts
.output_format
|=
384 DIFF_FORMAT_SUMMARY
| DIFF_FORMAT_DIFFSTAT
;
385 opts
.detect_rename
= DIFF_DETECT_RENAME
;
386 if (diff_use_color_default
> 0)
387 DIFF_OPT_SET(&opts
, COLOR_DIFF
);
388 if (diff_setup_done(&opts
) < 0)
389 die("diff_setup_done failed");
390 diff_tree_sha1(head
, new_head
, "", &opts
);
395 /* Run a post-merge hook */
396 run_hook(NULL
, "post-merge", squash
? "1" : "0", NULL
);
398 strbuf_release(&reflog_message
);
401 /* Get the name for the merge commit's message. */
402 static void merge_name(const char *remote
, struct strbuf
*msg
)
404 struct object
*remote_head
;
405 unsigned char branch_head
[20], buf_sha
[20];
406 struct strbuf buf
= STRBUF_INIT
;
407 struct strbuf bname
= STRBUF_INIT
;
412 strbuf_branchname(&bname
, remote
);
415 memset(branch_head
, 0, sizeof(branch_head
));
416 remote_head
= peel_to_type(remote
, 0, NULL
, OBJ_COMMIT
);
418 die("'%s' does not point to a commit", remote
);
420 if (dwim_ref(remote
, strlen(remote
), branch_head
, &found_ref
) > 0) {
421 if (!prefixcmp(found_ref
, "refs/heads/")) {
422 strbuf_addf(msg
, "%s\t\tbranch '%s' of .\n",
423 sha1_to_hex(branch_head
), remote
);
426 if (!prefixcmp(found_ref
, "refs/remotes/")) {
427 strbuf_addf(msg
, "%s\t\tremote-tracking branch '%s' of .\n",
428 sha1_to_hex(branch_head
), remote
);
433 /* See if remote matches <name>^^^.. or <name>~<number> */
434 for (len
= 0, ptr
= remote
+ strlen(remote
);
435 remote
< ptr
&& ptr
[-1] == '^';
442 ptr
= strrchr(remote
, '~');
444 int seen_nonzero
= 0;
447 while (*++ptr
&& isdigit(*ptr
)) {
448 seen_nonzero
|= (*ptr
!= '0');
452 len
= 0; /* not ...~<number> */
453 else if (seen_nonzero
)
456 early
= 1; /* "name~" is "name~1"! */
460 struct strbuf truname
= STRBUF_INIT
;
461 strbuf_addstr(&truname
, "refs/heads/");
462 strbuf_addstr(&truname
, remote
);
463 strbuf_setlen(&truname
, truname
.len
- len
);
464 if (resolve_ref(truname
.buf
, buf_sha
, 1, NULL
)) {
466 "%s\t\tbranch '%s'%s of .\n",
467 sha1_to_hex(remote_head
->sha1
),
469 (early
? " (early part)" : ""));
470 strbuf_release(&truname
);
475 if (!strcmp(remote
, "FETCH_HEAD") &&
476 !access(git_path("FETCH_HEAD"), R_OK
)) {
478 struct strbuf line
= STRBUF_INIT
;
481 fp
= fopen(git_path("FETCH_HEAD"), "r");
483 die_errno("could not open '%s' for reading",
484 git_path("FETCH_HEAD"));
485 strbuf_getline(&line
, fp
, '\n');
487 ptr
= strstr(line
.buf
, "\tnot-for-merge\t");
489 strbuf_remove(&line
, ptr
-line
.buf
+1, 13);
490 strbuf_addbuf(msg
, &line
);
491 strbuf_release(&line
);
494 strbuf_addf(msg
, "%s\t\tcommit '%s'\n",
495 sha1_to_hex(remote_head
->sha1
), remote
);
497 strbuf_release(&buf
);
498 strbuf_release(&bname
);
501 static int git_merge_config(const char *k
, const char *v
, void *cb
)
503 if (branch
&& !prefixcmp(k
, "branch.") &&
504 !prefixcmp(k
+ 7, branch
) &&
505 !strcmp(k
+ 7 + strlen(branch
), ".mergeoptions")) {
511 argc
= split_cmdline(buf
, &argv
);
513 die("Bad branch.%s.mergeoptions string: %s", branch
,
514 split_cmdline_strerror(argc
));
515 argv
= xrealloc(argv
, sizeof(*argv
) * (argc
+ 2));
516 memmove(argv
+ 1, argv
, sizeof(*argv
) * (argc
+ 1));
518 parse_options(argc
, argv
, NULL
, builtin_merge_options
,
519 builtin_merge_usage
, 0);
523 if (!strcmp(k
, "merge.diffstat") || !strcmp(k
, "merge.stat"))
524 show_diffstat
= git_config_bool(k
, v
);
525 else if (!strcmp(k
, "pull.twohead"))
526 return git_config_string(&pull_twohead
, k
, v
);
527 else if (!strcmp(k
, "pull.octopus"))
528 return git_config_string(&pull_octopus
, k
, v
);
529 else if (!strcmp(k
, "merge.renormalize"))
530 option_renormalize
= git_config_bool(k
, v
);
531 else if (!strcmp(k
, "merge.log") || !strcmp(k
, "merge.summary")) {
533 shortlog_len
= git_config_bool_or_int(k
, v
, &is_bool
);
534 if (!is_bool
&& shortlog_len
< 0)
535 return error("%s: negative length %s", k
, v
);
536 if (is_bool
&& shortlog_len
)
537 shortlog_len
= DEFAULT_MERGE_LOG_LEN
;
540 return git_diff_ui_config(k
, v
, cb
);
543 static int read_tree_trivial(unsigned char *common
, unsigned char *head
,
547 struct tree
*trees
[MAX_UNPACK_TREES
];
548 struct tree_desc t
[MAX_UNPACK_TREES
];
549 struct unpack_trees_options opts
;
551 memset(&opts
, 0, sizeof(opts
));
553 opts
.src_index
= &the_index
;
554 opts
.dst_index
= &the_index
;
556 opts
.verbose_update
= 1;
557 opts
.trivial_merges_only
= 1;
559 trees
[nr_trees
] = parse_tree_indirect(common
);
560 if (!trees
[nr_trees
++])
562 trees
[nr_trees
] = parse_tree_indirect(head
);
563 if (!trees
[nr_trees
++])
565 trees
[nr_trees
] = parse_tree_indirect(one
);
566 if (!trees
[nr_trees
++])
568 opts
.fn
= threeway_merge
;
569 cache_tree_free(&active_cache_tree
);
570 for (i
= 0; i
< nr_trees
; i
++) {
571 parse_tree(trees
[i
]);
572 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
574 if (unpack_trees(nr_trees
, t
, &opts
))
579 static void write_tree_trivial(unsigned char *sha1
)
581 if (write_cache_as_tree(sha1
, 0, NULL
))
582 die("git write-tree failed to write a tree");
585 int try_merge_command(const char *strategy
, struct commit_list
*common
,
586 const char *head_arg
, struct commit_list
*remotes
)
589 int i
= 0, x
= 0, ret
;
590 struct commit_list
*j
;
591 struct strbuf buf
= STRBUF_INIT
;
593 args
= xmalloc((4 + xopts_nr
+ commit_list_count(common
) +
594 commit_list_count(remotes
)) * sizeof(char *));
595 strbuf_addf(&buf
, "merge-%s", strategy
);
597 for (x
= 0; x
< xopts_nr
; x
++) {
598 char *s
= xmalloc(strlen(xopts
[x
])+2+1);
600 strcpy(s
+2, xopts
[x
]);
603 for (j
= common
; j
; j
= j
->next
)
604 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
606 args
[i
++] = head_arg
;
607 for (j
= remotes
; j
; j
= j
->next
)
608 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
610 ret
= run_command_v_opt(args
, RUN_GIT_CMD
);
611 strbuf_release(&buf
);
613 for (x
= 0; x
< xopts_nr
; x
++)
614 free((void *)args
[i
++]);
615 for (j
= common
; j
; j
= j
->next
)
616 free((void *)args
[i
++]);
618 for (j
= remotes
; j
; j
= j
->next
)
619 free((void *)args
[i
++]);
622 if (read_cache() < 0)
623 die("failed to read the cache");
624 resolve_undo_clear();
629 static int try_merge_strategy(const char *strategy
, struct commit_list
*common
,
630 const char *head_arg
)
633 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
635 index_fd
= hold_locked_index(lock
, 1);
636 refresh_cache(REFRESH_QUIET
);
637 if (active_cache_changed
&&
638 (write_cache(index_fd
, active_cache
, active_nr
) ||
639 commit_locked_index(lock
)))
640 return error("Unable to write index.");
641 rollback_lock_file(lock
);
643 if (!strcmp(strategy
, "recursive") || !strcmp(strategy
, "subtree")) {
645 struct commit
*result
;
646 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
648 struct commit_list
*reversed
= NULL
;
649 struct merge_options o
;
650 struct commit_list
*j
;
652 if (remoteheads
->next
) {
653 error("Not handling anything other than two heads merge.");
657 init_merge_options(&o
);
658 if (!strcmp(strategy
, "subtree"))
659 o
.subtree_shift
= "";
661 o
.renormalize
= option_renormalize
;
663 for (x
= 0; x
< xopts_nr
; x
++)
664 if (parse_merge_opt(&o
, xopts
[x
]))
665 die("Unknown option for merge-recursive: -X%s", xopts
[x
]);
667 o
.branch1
= head_arg
;
668 o
.branch2
= remoteheads
->item
->util
;
670 for (j
= common
; j
; j
= j
->next
)
671 commit_list_insert(j
->item
, &reversed
);
673 index_fd
= hold_locked_index(lock
, 1);
674 clean
= merge_recursive(&o
, lookup_commit(head
),
675 remoteheads
->item
, reversed
, &result
);
676 if (active_cache_changed
&&
677 (write_cache(index_fd
, active_cache
, active_nr
) ||
678 commit_locked_index(lock
)))
679 die ("unable to write %s", get_index_file());
680 rollback_lock_file(lock
);
681 return clean
? 0 : 1;
683 return try_merge_command(strategy
, common
, head_arg
, remoteheads
);
687 static void count_diff_files(struct diff_queue_struct
*q
,
688 struct diff_options
*opt
, void *data
)
695 static int count_unmerged_entries(void)
699 for (i
= 0; i
< active_nr
; i
++)
700 if (ce_stage(active_cache
[i
]))
706 int checkout_fast_forward(const unsigned char *head
, const unsigned char *remote
)
708 struct tree
*trees
[MAX_UNPACK_TREES
];
709 struct unpack_trees_options opts
;
710 struct tree_desc t
[MAX_UNPACK_TREES
];
711 int i
, fd
, nr_trees
= 0;
712 struct dir_struct dir
;
713 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
715 refresh_cache(REFRESH_QUIET
);
717 fd
= hold_locked_index(lock_file
, 1);
719 memset(&trees
, 0, sizeof(trees
));
720 memset(&opts
, 0, sizeof(opts
));
721 memset(&t
, 0, sizeof(t
));
722 memset(&dir
, 0, sizeof(dir
));
723 dir
.flags
|= DIR_SHOW_IGNORED
;
724 dir
.exclude_per_dir
= ".gitignore";
728 opts
.src_index
= &the_index
;
729 opts
.dst_index
= &the_index
;
731 opts
.verbose_update
= 1;
733 opts
.fn
= twoway_merge
;
734 setup_unpack_trees_porcelain(&opts
, "merge");
736 trees
[nr_trees
] = parse_tree_indirect(head
);
737 if (!trees
[nr_trees
++])
739 trees
[nr_trees
] = parse_tree_indirect(remote
);
740 if (!trees
[nr_trees
++])
742 for (i
= 0; i
< nr_trees
; i
++) {
743 parse_tree(trees
[i
]);
744 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
746 if (unpack_trees(nr_trees
, t
, &opts
))
748 if (write_cache(fd
, active_cache
, active_nr
) ||
749 commit_locked_index(lock_file
))
750 die("unable to write new index file");
754 static void split_merge_strategies(const char *string
, struct strategy
**list
,
762 buf
= xstrdup(string
);
767 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
768 (*list
)[(*nr
)++].name
= xstrdup(q
);
773 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
774 (*list
)[(*nr
)++].name
= xstrdup(q
);
780 static void add_strategies(const char *string
, unsigned attr
)
782 struct strategy
*list
= NULL
;
783 int list_alloc
= 0, list_nr
= 0, i
;
785 memset(&list
, 0, sizeof(list
));
786 split_merge_strategies(string
, &list
, &list_nr
, &list_alloc
);
788 for (i
= 0; i
< list_nr
; i
++)
789 append_strategy(get_strategy(list
[i
].name
));
792 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
793 if (all_strategy
[i
].attr
& attr
)
794 append_strategy(&all_strategy
[i
]);
798 static int merge_trivial(void)
800 unsigned char result_tree
[20], result_commit
[20];
801 struct commit_list
*parent
= xmalloc(sizeof(*parent
));
803 write_tree_trivial(result_tree
);
804 printf("Wonderful.\n");
805 parent
->item
= lookup_commit(head
);
806 parent
->next
= xmalloc(sizeof(*parent
->next
));
807 parent
->next
->item
= remoteheads
->item
;
808 parent
->next
->next
= NULL
;
809 commit_tree(merge_msg
.buf
, result_tree
, parent
, result_commit
, NULL
);
810 finish(result_commit
, "In-index merge");
815 static int finish_automerge(struct commit_list
*common
,
816 unsigned char *result_tree
,
817 const char *wt_strategy
)
819 struct commit_list
*parents
= NULL
, *j
;
820 struct strbuf buf
= STRBUF_INIT
;
821 unsigned char result_commit
[20];
823 free_commit_list(common
);
824 if (allow_fast_forward
) {
825 parents
= remoteheads
;
826 commit_list_insert(lookup_commit(head
), &parents
);
827 parents
= reduce_heads(parents
);
829 struct commit_list
**pptr
= &parents
;
831 pptr
= &commit_list_insert(lookup_commit(head
),
833 for (j
= remoteheads
; j
; j
= j
->next
)
834 pptr
= &commit_list_insert(j
->item
, pptr
)->next
;
836 free_commit_list(remoteheads
);
837 strbuf_addch(&merge_msg
, '\n');
838 commit_tree(merge_msg
.buf
, result_tree
, parents
, result_commit
, NULL
);
839 strbuf_addf(&buf
, "Merge made by %s.", wt_strategy
);
840 finish(result_commit
, buf
.buf
);
841 strbuf_release(&buf
);
846 static int suggest_conflicts(int renormalizing
)
851 fp
= fopen(git_path("MERGE_MSG"), "a");
853 die_errno("Could not open '%s' for writing",
854 git_path("MERGE_MSG"));
855 fprintf(fp
, "\nConflicts:\n");
856 for (pos
= 0; pos
< active_nr
; pos
++) {
857 struct cache_entry
*ce
= active_cache
[pos
];
860 fprintf(fp
, "\t%s\n", ce
->name
);
861 while (pos
+ 1 < active_nr
&&
863 active_cache
[pos
+ 1]->name
))
868 rerere(allow_rerere_auto
);
869 printf("Automatic merge failed; "
870 "fix conflicts and then commit the result.\n");
874 static struct commit
*is_old_style_invocation(int argc
, const char **argv
)
876 struct commit
*second_token
= NULL
;
878 unsigned char second_sha1
[20];
880 if (get_sha1(argv
[1], second_sha1
))
882 second_token
= lookup_commit_reference_gently(second_sha1
, 0);
884 die("'%s' is not a commit", argv
[1]);
885 if (hashcmp(second_token
->object
.sha1
, head
))
891 static int evaluate_result(void)
896 /* Check how many files differ. */
897 init_revisions(&rev
, "");
898 setup_revisions(0, NULL
, &rev
, NULL
);
899 rev
.diffopt
.output_format
|=
900 DIFF_FORMAT_CALLBACK
;
901 rev
.diffopt
.format_callback
= count_diff_files
;
902 rev
.diffopt
.format_callback_data
= &cnt
;
903 run_diff_files(&rev
, 0);
906 * Check how many unmerged entries are
909 cnt
+= count_unmerged_entries();
914 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
916 unsigned char result_tree
[20];
917 struct strbuf buf
= STRBUF_INIT
;
918 const char *head_arg
;
919 int flag
, head_invalid
= 0, i
;
920 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
921 struct commit_list
*common
= NULL
;
922 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
923 struct commit_list
**remotes
= &remoteheads
;
925 if (argc
== 2 && !strcmp(argv
[1], "-h"))
926 usage_with_options(builtin_merge_usage
, builtin_merge_options
);
929 * Check if we are _not_ on a detached HEAD, i.e. if there is a
932 branch
= resolve_ref("HEAD", head
, 0, &flag
);
933 if (branch
&& !prefixcmp(branch
, "refs/heads/"))
935 if (is_null_sha1(head
))
938 git_config(git_merge_config
, NULL
);
941 if (diff_use_color_default
== -1)
942 diff_use_color_default
= git_use_color_default
;
944 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
945 builtin_merge_usage
, 0);
947 if (abort_current_merge
) {
949 const char *nargv
[] = {"reset", "--merge", NULL
};
951 if (!file_exists(git_path("MERGE_HEAD")))
952 die("There is no merge to abort (MERGE_HEAD missing).");
954 /* Invoke 'git reset --merge' */
955 return cmd_reset(nargc
, nargv
, prefix
);
958 if (read_cache_unmerged())
959 die_resolve_conflict("merge");
961 if (file_exists(git_path("MERGE_HEAD"))) {
963 * There is no unmerged entry, don't advise 'git
964 * add/rm <file>', just 'git commit'.
966 if (advice_resolve_conflict
)
967 die("You have not concluded your merge (MERGE_HEAD exists).\n"
968 "Please, commit your changes before you can merge.");
970 die("You have not concluded your merge (MERGE_HEAD exists).");
972 resolve_undo_clear();
978 if (!allow_fast_forward
)
979 die("You cannot combine --squash with --no-ff.");
983 if (!allow_fast_forward
&& fast_forward_only
)
984 die("You cannot combine --no-ff with --ff-only.");
987 usage_with_options(builtin_merge_usage
,
988 builtin_merge_options
);
991 * This could be traditional "merge <msg> HEAD <commit>..." and
992 * the way we can tell it is to see if the second token is HEAD,
993 * but some people might have misused the interface and used a
994 * committish that is the same as HEAD there instead.
995 * Traditional format never would have "-m" so it is an
996 * additional safety measure to check for it.
999 if (!have_message
&& is_old_style_invocation(argc
, argv
)) {
1000 strbuf_addstr(&merge_msg
, argv
[0]);
1004 } else if (head_invalid
) {
1005 struct object
*remote_head
;
1007 * If the merged head is a valid one there is no reason
1008 * to forbid "git merge" into a branch yet to be born.
1009 * We do the same for "git pull".
1012 die("Can merge only exactly one commit into "
1015 die("Squash commit into empty head not supported yet");
1016 if (!allow_fast_forward
)
1017 die("Non-fast-forward commit does not make sense into "
1019 remote_head
= peel_to_type(argv
[0], 0, NULL
, OBJ_COMMIT
);
1021 die("%s - not something we can merge", argv
[0]);
1022 update_ref("initial pull", "HEAD", remote_head
->sha1
, NULL
, 0,
1024 read_empty(remote_head
->sha1
, 0);
1027 struct strbuf merge_names
= STRBUF_INIT
;
1029 /* We are invoked directly as the first-class UI. */
1033 * All the rest are the commits being merged;
1034 * prepare the standard merge summary message to
1035 * be appended to the given message. If remote
1036 * is invalid we will die later in the common
1037 * codepath so we discard the error in this
1040 for (i
= 0; i
< argc
; i
++)
1041 merge_name(argv
[i
], &merge_names
);
1043 if (!have_message
|| shortlog_len
) {
1044 fmt_merge_msg(&merge_names
, &merge_msg
, !have_message
,
1047 strbuf_setlen(&merge_msg
, merge_msg
.len
- 1);
1051 if (head_invalid
|| !argc
)
1052 usage_with_options(builtin_merge_usage
,
1053 builtin_merge_options
);
1055 strbuf_addstr(&buf
, "merge");
1056 for (i
= 0; i
< argc
; i
++)
1057 strbuf_addf(&buf
, " %s", argv
[i
]);
1058 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
1061 for (i
= 0; i
< argc
; i
++) {
1063 struct commit
*commit
;
1065 o
= peel_to_type(argv
[i
], 0, NULL
, OBJ_COMMIT
);
1067 die("%s - not something we can merge", argv
[i
]);
1068 commit
= lookup_commit(o
->sha1
);
1069 commit
->util
= (void *)argv
[i
];
1070 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1072 strbuf_addf(&buf
, "GITHEAD_%s", sha1_to_hex(o
->sha1
));
1073 setenv(buf
.buf
, argv
[i
], 1);
1077 if (!use_strategies
) {
1078 if (!remoteheads
->next
)
1079 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
1081 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
1084 for (i
= 0; i
< use_strategies_nr
; i
++) {
1085 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
1086 allow_fast_forward
= 0;
1087 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
1091 if (!remoteheads
->next
)
1092 common
= get_merge_bases(lookup_commit(head
),
1093 remoteheads
->item
, 1);
1095 struct commit_list
*list
= remoteheads
;
1096 commit_list_insert(lookup_commit(head
), &list
);
1097 common
= get_octopus_merge_bases(list
);
1101 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head
, NULL
, 0,
1105 ; /* No common ancestors found. We need a real merge. */
1106 else if (!remoteheads
->next
&& !common
->next
&&
1107 common
->item
== remoteheads
->item
) {
1109 * If head can reach all the merge then we are up to date.
1110 * but first the most common case of merging one remote.
1112 finish_up_to_date("Already up-to-date.");
1114 } else if (allow_fast_forward
&& !remoteheads
->next
&&
1116 !hashcmp(common
->item
->object
.sha1
, head
)) {
1117 /* Again the most common case of merging one remote. */
1118 struct strbuf msg
= STRBUF_INIT
;
1122 strcpy(hex
, find_unique_abbrev(head
, DEFAULT_ABBREV
));
1125 printf("Updating %s..%s\n",
1127 find_unique_abbrev(remoteheads
->item
->object
.sha1
,
1129 strbuf_addstr(&msg
, "Fast-forward");
1132 " (no commit created; -m option ignored)");
1133 o
= peel_to_type(sha1_to_hex(remoteheads
->item
->object
.sha1
),
1134 0, NULL
, OBJ_COMMIT
);
1138 if (checkout_fast_forward(head
, remoteheads
->item
->object
.sha1
))
1141 finish(o
->sha1
, msg
.buf
);
1144 } else if (!remoteheads
->next
&& common
->next
)
1147 * We are not doing octopus and not fast-forward. Need
1150 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1152 * We are not doing octopus, not fast-forward, and have
1155 refresh_cache(REFRESH_QUIET
);
1156 if (allow_trivial
&& !fast_forward_only
) {
1157 /* See if it is really trivial. */
1158 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1159 printf("Trying really trivial in-index merge...\n");
1160 if (!read_tree_trivial(common
->item
->object
.sha1
,
1161 head
, remoteheads
->item
->object
.sha1
))
1162 return merge_trivial();
1167 * An octopus. If we can reach all the remote we are up
1171 struct commit_list
*j
;
1173 for (j
= remoteheads
; j
; j
= j
->next
) {
1174 struct commit_list
*common_one
;
1177 * Here we *have* to calculate the individual
1178 * merge_bases again, otherwise "git merge HEAD^
1179 * HEAD^^" would be missed.
1181 common_one
= get_merge_bases(lookup_commit(head
),
1183 if (hashcmp(common_one
->item
->object
.sha1
,
1184 j
->item
->object
.sha1
)) {
1190 finish_up_to_date("Already up-to-date. Yeeah!");
1195 if (fast_forward_only
)
1196 die("Not possible to fast-forward, aborting.");
1198 /* We are going to make a new commit. */
1199 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1202 * At this point, we need a real merge. No matter what strategy
1203 * we use, it would operate on the index, possibly affecting the
1204 * working tree, and when resolved cleanly, have the desired
1205 * tree in the index -- this means that the index must be in
1206 * sync with the head commit. The strategies are responsible
1209 if (use_strategies_nr
!= 1) {
1211 * Stash away the local changes so that we can try more
1216 memcpy(stash
, null_sha1
, 20);
1219 for (i
= 0; i
< use_strategies_nr
; i
++) {
1222 printf("Rewinding the tree to pristine...\n");
1225 if (use_strategies_nr
!= 1)
1226 printf("Trying merge strategy %s...\n",
1227 use_strategies
[i
]->name
);
1229 * Remember which strategy left the state in the working
1232 wt_strategy
= use_strategies
[i
]->name
;
1234 ret
= try_merge_strategy(use_strategies
[i
]->name
,
1236 if (!option_commit
&& !ret
) {
1239 * This is necessary here just to avoid writing
1240 * the tree, but later we will *not* exit with
1241 * status code 1 because merge_was_ok is set.
1248 * The backend exits with 1 when conflicts are
1249 * left to be resolved, with 2 when it does not
1250 * handle the given merge at all.
1253 int cnt
= evaluate_result();
1255 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1256 best_strategy
= use_strategies
[i
]->name
;
1266 /* Automerge succeeded. */
1267 write_tree_trivial(result_tree
);
1268 automerge_was_ok
= 1;
1273 * If we have a resulting tree, that means the strategy module
1274 * auto resolved the merge cleanly.
1276 if (automerge_was_ok
)
1277 return finish_automerge(common
, result_tree
, wt_strategy
);
1280 * Pick the result from the best strategy and have the user fix
1283 if (!best_strategy
) {
1285 if (use_strategies_nr
> 1)
1287 "No merge strategy handled the merge.\n");
1289 fprintf(stderr
, "Merge with strategy %s failed.\n",
1290 use_strategies
[0]->name
);
1292 } else if (best_strategy
== wt_strategy
)
1293 ; /* We already have its result in the working tree. */
1295 printf("Rewinding the tree to pristine...\n");
1297 printf("Using the %s to prepare resolving by hand.\n",
1299 try_merge_strategy(best_strategy
, common
, head_arg
);
1306 struct commit_list
*j
;
1308 for (j
= remoteheads
; j
; j
= j
->next
)
1309 strbuf_addf(&buf
, "%s\n",
1310 sha1_to_hex(j
->item
->object
.sha1
));
1311 fd
= open(git_path("MERGE_HEAD"), O_WRONLY
| O_CREAT
, 0666);
1313 die_errno("Could not open '%s' for writing",
1314 git_path("MERGE_HEAD"));
1315 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1316 die_errno("Could not write to '%s'", git_path("MERGE_HEAD"));
1318 strbuf_addch(&merge_msg
, '\n');
1319 fd
= open(git_path("MERGE_MSG"), O_WRONLY
| O_CREAT
, 0666);
1321 die_errno("Could not open '%s' for writing",
1322 git_path("MERGE_MSG"));
1323 if (write_in_full(fd
, merge_msg
.buf
, merge_msg
.len
) !=
1325 die_errno("Could not write to '%s'", git_path("MERGE_MSG"));
1327 fd
= open(git_path("MERGE_MODE"), O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
1329 die_errno("Could not open '%s' for writing",
1330 git_path("MERGE_MODE"));
1332 if (!allow_fast_forward
)
1333 strbuf_addf(&buf
, "no-ff");
1334 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1335 die_errno("Could not write to '%s'", git_path("MERGE_MODE"));
1340 fprintf(stderr
, "Automatic merge went well; "
1341 "stopped before committing as requested\n");
1344 return suggest_conflicts(option_renormalize
);