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
;
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 { OPTION_INTEGER
, 0, "log", &shortlog_len
, "n",
181 "add (at most <n>) entries from shortlog to merge commit message",
182 PARSE_OPT_OPTARG
, NULL
, DEFAULT_MERGE_LOG_LEN
},
183 OPT_BOOLEAN(0, "squash", &squash
,
184 "create a single commit instead of doing a merge"),
185 OPT_BOOLEAN(0, "commit", &option_commit
,
186 "perform a commit if the merge succeeds (default)"),
187 OPT_BOOLEAN(0, "ff", &allow_fast_forward
,
188 "allow fast-forward (default)"),
189 OPT_BOOLEAN(0, "ff-only", &fast_forward_only
,
190 "abort if fast-forward is not possible"),
191 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto
),
192 OPT_CALLBACK('s', "strategy", &use_strategies
, "strategy",
193 "merge strategy to use", option_parse_strategy
),
194 OPT_CALLBACK('X', "strategy-option", &xopts
, "option=value",
195 "option for selected merge strategy", option_parse_x
),
196 OPT_CALLBACK('m', "message", &merge_msg
, "message",
197 "message to be used for the merge commit (if any)",
198 option_parse_message
),
199 OPT__VERBOSITY(&verbosity
),
203 /* Cleans up metadata that is uninteresting after a succeeded merge. */
204 static void drop_save(void)
206 unlink(git_path("MERGE_HEAD"));
207 unlink(git_path("MERGE_MSG"));
208 unlink(git_path("MERGE_MODE"));
211 static void save_state(void)
214 struct child_process cp
;
215 struct strbuf buffer
= STRBUF_INIT
;
216 const char *argv
[] = {"stash", "create", NULL
};
218 memset(&cp
, 0, sizeof(cp
));
223 if (start_command(&cp
))
224 die("could not run stash.");
225 len
= strbuf_read(&buffer
, cp
.out
, 1024);
228 if (finish_command(&cp
) || len
< 0)
232 strbuf_setlen(&buffer
, buffer
.len
-1);
233 if (get_sha1(buffer
.buf
, stash
))
234 die("not a valid object: %s", buffer
.buf
);
237 static void reset_hard(unsigned const char *sha1
, int verbose
)
242 args
[i
++] = "read-tree";
245 args
[i
++] = "--reset";
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 restore_state(void)
256 struct strbuf sb
= STRBUF_INIT
;
257 const char *args
[] = { "stash", "apply", NULL
, NULL
};
259 if (is_null_sha1(stash
))
264 args
[2] = sha1_to_hex(stash
);
267 * It is OK to ignore error here, for example when there was
268 * nothing to restore.
270 run_command_v_opt(args
, RUN_GIT_CMD
);
273 refresh_cache(REFRESH_QUIET
);
276 /* This is called when no merge was necessary. */
277 static void finish_up_to_date(const char *msg
)
280 printf("%s%s\n", squash
? " (nothing to squash)" : "", msg
);
284 static void squash_message(void)
287 struct commit
*commit
;
288 struct strbuf out
= STRBUF_INIT
;
289 struct commit_list
*j
;
291 struct pretty_print_context ctx
= {0};
293 printf("Squash commit -- not updating HEAD\n");
294 fd
= open(git_path("SQUASH_MSG"), O_WRONLY
| O_CREAT
, 0666);
296 die_errno("Could not write to '%s'", git_path("SQUASH_MSG"));
298 init_revisions(&rev
, NULL
);
299 rev
.ignore_merges
= 1;
300 rev
.commit_format
= CMIT_FMT_MEDIUM
;
302 commit
= lookup_commit(head
);
303 commit
->object
.flags
|= UNINTERESTING
;
304 add_pending_object(&rev
, &commit
->object
, NULL
);
306 for (j
= remoteheads
; j
; j
= j
->next
)
307 add_pending_object(&rev
, &j
->item
->object
, NULL
);
309 setup_revisions(0, NULL
, &rev
, NULL
);
310 if (prepare_revision_walk(&rev
))
311 die("revision walk setup failed");
313 ctx
.abbrev
= rev
.abbrev
;
314 ctx
.date_mode
= rev
.date_mode
;
316 strbuf_addstr(&out
, "Squashed commit of the following:\n");
317 while ((commit
= get_revision(&rev
)) != NULL
) {
318 strbuf_addch(&out
, '\n');
319 strbuf_addf(&out
, "commit %s\n",
320 sha1_to_hex(commit
->object
.sha1
));
321 pretty_print_commit(rev
.commit_format
, commit
, &out
, &ctx
);
323 if (write(fd
, out
.buf
, out
.len
) < 0)
324 die_errno("Writing SQUASH_MSG");
326 die_errno("Finishing SQUASH_MSG");
327 strbuf_release(&out
);
330 static void finish(const unsigned char *new_head
, const char *msg
)
332 struct strbuf reflog_message
= STRBUF_INIT
;
335 strbuf_addstr(&reflog_message
, getenv("GIT_REFLOG_ACTION"));
339 strbuf_addf(&reflog_message
, "%s: %s",
340 getenv("GIT_REFLOG_ACTION"), msg
);
345 if (verbosity
>= 0 && !merge_msg
.len
)
346 printf("No merge message -- not updating HEAD\n");
348 const char *argv_gc_auto
[] = { "gc", "--auto", NULL
};
349 update_ref(reflog_message
.buf
, "HEAD",
353 * We ignore errors in 'gc --auto', since the
354 * user should see them.
356 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
359 if (new_head
&& show_diffstat
) {
360 struct diff_options opts
;
362 opts
.output_format
|=
363 DIFF_FORMAT_SUMMARY
| DIFF_FORMAT_DIFFSTAT
;
364 opts
.detect_rename
= DIFF_DETECT_RENAME
;
365 if (diff_use_color_default
> 0)
366 DIFF_OPT_SET(&opts
, COLOR_DIFF
);
367 if (diff_setup_done(&opts
) < 0)
368 die("diff_setup_done failed");
369 diff_tree_sha1(head
, new_head
, "", &opts
);
374 /* Run a post-merge hook */
375 run_hook(NULL
, "post-merge", squash
? "1" : "0", NULL
);
377 strbuf_release(&reflog_message
);
380 /* Get the name for the merge commit's message. */
381 static void merge_name(const char *remote
, struct strbuf
*msg
)
383 struct object
*remote_head
;
384 unsigned char branch_head
[20], buf_sha
[20];
385 struct strbuf buf
= STRBUF_INIT
;
386 struct strbuf bname
= STRBUF_INIT
;
391 strbuf_branchname(&bname
, remote
);
394 memset(branch_head
, 0, sizeof(branch_head
));
395 remote_head
= peel_to_type(remote
, 0, NULL
, OBJ_COMMIT
);
397 die("'%s' does not point to a commit", remote
);
399 if (dwim_ref(remote
, strlen(remote
), branch_head
, &found_ref
) > 0) {
400 if (!prefixcmp(found_ref
, "refs/heads/")) {
401 strbuf_addf(msg
, "%s\t\tbranch '%s' of .\n",
402 sha1_to_hex(branch_head
), remote
);
405 if (!prefixcmp(found_ref
, "refs/remotes/")) {
406 strbuf_addf(msg
, "%s\t\tremote branch '%s' of .\n",
407 sha1_to_hex(branch_head
), remote
);
412 /* See if remote matches <name>^^^.. or <name>~<number> */
413 for (len
= 0, ptr
= remote
+ strlen(remote
);
414 remote
< ptr
&& ptr
[-1] == '^';
421 ptr
= strrchr(remote
, '~');
423 int seen_nonzero
= 0;
426 while (*++ptr
&& isdigit(*ptr
)) {
427 seen_nonzero
|= (*ptr
!= '0');
431 len
= 0; /* not ...~<number> */
432 else if (seen_nonzero
)
435 early
= 1; /* "name~" is "name~1"! */
439 struct strbuf truname
= STRBUF_INIT
;
440 strbuf_addstr(&truname
, "refs/heads/");
441 strbuf_addstr(&truname
, remote
);
442 strbuf_setlen(&truname
, truname
.len
- len
);
443 if (resolve_ref(truname
.buf
, buf_sha
, 1, NULL
)) {
445 "%s\t\tbranch '%s'%s of .\n",
446 sha1_to_hex(remote_head
->sha1
),
448 (early
? " (early part)" : ""));
449 strbuf_release(&truname
);
454 if (!strcmp(remote
, "FETCH_HEAD") &&
455 !access(git_path("FETCH_HEAD"), R_OK
)) {
457 struct strbuf line
= STRBUF_INIT
;
460 fp
= fopen(git_path("FETCH_HEAD"), "r");
462 die_errno("could not open '%s' for reading",
463 git_path("FETCH_HEAD"));
464 strbuf_getline(&line
, fp
, '\n');
466 ptr
= strstr(line
.buf
, "\tnot-for-merge\t");
468 strbuf_remove(&line
, ptr
-line
.buf
+1, 13);
469 strbuf_addbuf(msg
, &line
);
470 strbuf_release(&line
);
473 strbuf_addf(msg
, "%s\t\tcommit '%s'\n",
474 sha1_to_hex(remote_head
->sha1
), remote
);
476 strbuf_release(&buf
);
477 strbuf_release(&bname
);
480 static int git_merge_config(const char *k
, const char *v
, void *cb
)
482 if (branch
&& !prefixcmp(k
, "branch.") &&
483 !prefixcmp(k
+ 7, branch
) &&
484 !strcmp(k
+ 7 + strlen(branch
), ".mergeoptions")) {
490 argc
= split_cmdline(buf
, &argv
);
492 die("Bad branch.%s.mergeoptions string: %s", branch
,
493 split_cmdline_strerror(argc
));
494 argv
= xrealloc(argv
, sizeof(*argv
) * (argc
+ 2));
495 memmove(argv
+ 1, argv
, sizeof(*argv
) * (argc
+ 1));
497 parse_options(argc
, argv
, NULL
, builtin_merge_options
,
498 builtin_merge_usage
, 0);
502 if (!strcmp(k
, "merge.diffstat") || !strcmp(k
, "merge.stat"))
503 show_diffstat
= git_config_bool(k
, v
);
504 else if (!strcmp(k
, "pull.twohead"))
505 return git_config_string(&pull_twohead
, k
, v
);
506 else if (!strcmp(k
, "pull.octopus"))
507 return git_config_string(&pull_octopus
, k
, v
);
508 else if (!strcmp(k
, "merge.renormalize"))
509 option_renormalize
= git_config_bool(k
, v
);
510 else if (!strcmp(k
, "merge.log") || !strcmp(k
, "merge.summary")) {
512 shortlog_len
= git_config_bool_or_int(k
, v
, &is_bool
);
513 if (!is_bool
&& shortlog_len
< 0)
514 return error("%s: negative length %s", k
, v
);
515 if (is_bool
&& shortlog_len
)
516 shortlog_len
= DEFAULT_MERGE_LOG_LEN
;
519 return git_diff_ui_config(k
, v
, cb
);
522 static int read_tree_trivial(unsigned char *common
, unsigned char *head
,
526 struct tree
*trees
[MAX_UNPACK_TREES
];
527 struct tree_desc t
[MAX_UNPACK_TREES
];
528 struct unpack_trees_options opts
;
530 memset(&opts
, 0, sizeof(opts
));
532 opts
.src_index
= &the_index
;
533 opts
.dst_index
= &the_index
;
535 opts
.verbose_update
= 1;
536 opts
.trivial_merges_only
= 1;
538 trees
[nr_trees
] = parse_tree_indirect(common
);
539 if (!trees
[nr_trees
++])
541 trees
[nr_trees
] = parse_tree_indirect(head
);
542 if (!trees
[nr_trees
++])
544 trees
[nr_trees
] = parse_tree_indirect(one
);
545 if (!trees
[nr_trees
++])
547 opts
.fn
= threeway_merge
;
548 cache_tree_free(&active_cache_tree
);
549 for (i
= 0; i
< nr_trees
; i
++) {
550 parse_tree(trees
[i
]);
551 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
553 if (unpack_trees(nr_trees
, t
, &opts
))
558 static void write_tree_trivial(unsigned char *sha1
)
560 if (write_cache_as_tree(sha1
, 0, NULL
))
561 die("git write-tree failed to write a tree");
564 int try_merge_command(const char *strategy
, struct commit_list
*common
,
565 const char *head_arg
, struct commit_list
*remotes
)
568 int i
= 0, x
= 0, ret
;
569 struct commit_list
*j
;
570 struct strbuf buf
= STRBUF_INIT
;
572 args
= xmalloc((4 + xopts_nr
+ commit_list_count(common
) +
573 commit_list_count(remotes
)) * sizeof(char *));
574 strbuf_addf(&buf
, "merge-%s", strategy
);
576 for (x
= 0; x
< xopts_nr
; x
++) {
577 char *s
= xmalloc(strlen(xopts
[x
])+2+1);
579 strcpy(s
+2, xopts
[x
]);
582 for (j
= common
; j
; j
= j
->next
)
583 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
585 args
[i
++] = head_arg
;
586 for (j
= remotes
; j
; j
= j
->next
)
587 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
589 ret
= run_command_v_opt(args
, RUN_GIT_CMD
);
590 strbuf_release(&buf
);
592 for (x
= 0; x
< xopts_nr
; x
++)
593 free((void *)args
[i
++]);
594 for (j
= common
; j
; j
= j
->next
)
595 free((void *)args
[i
++]);
597 for (j
= remotes
; j
; j
= j
->next
)
598 free((void *)args
[i
++]);
601 if (read_cache() < 0)
602 die("failed to read the cache");
603 resolve_undo_clear();
608 static int try_merge_strategy(const char *strategy
, struct commit_list
*common
,
609 const char *head_arg
)
612 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
614 index_fd
= hold_locked_index(lock
, 1);
615 refresh_cache(REFRESH_QUIET
);
616 if (active_cache_changed
&&
617 (write_cache(index_fd
, active_cache
, active_nr
) ||
618 commit_locked_index(lock
)))
619 return error("Unable to write index.");
620 rollback_lock_file(lock
);
622 if (!strcmp(strategy
, "recursive") || !strcmp(strategy
, "subtree")) {
624 struct commit
*result
;
625 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
627 struct commit_list
*reversed
= NULL
;
628 struct merge_options o
;
629 struct commit_list
*j
;
631 if (remoteheads
->next
) {
632 error("Not handling anything other than two heads merge.");
636 init_merge_options(&o
);
637 if (!strcmp(strategy
, "subtree"))
638 o
.subtree_shift
= "";
640 o
.renormalize
= option_renormalize
;
643 * NEEDSWORK: merge with table in builtin/merge-recursive
645 for (x
= 0; x
< xopts_nr
; x
++) {
646 if (!strcmp(xopts
[x
], "ours"))
647 o
.recursive_variant
= MERGE_RECURSIVE_OURS
;
648 else if (!strcmp(xopts
[x
], "theirs"))
649 o
.recursive_variant
= MERGE_RECURSIVE_THEIRS
;
650 else if (!strcmp(xopts
[x
], "subtree"))
651 o
.subtree_shift
= "";
652 else if (!prefixcmp(xopts
[x
], "subtree="))
653 o
.subtree_shift
= xopts
[x
]+8;
654 else if (!strcmp(xopts
[x
], "renormalize"))
656 else if (!strcmp(xopts
[x
], "no-renormalize"))
659 die("Unknown option for merge-recursive: -X%s", xopts
[x
]);
662 o
.branch1
= head_arg
;
663 o
.branch2
= remoteheads
->item
->util
;
665 for (j
= common
; j
; j
= j
->next
)
666 commit_list_insert(j
->item
, &reversed
);
668 index_fd
= hold_locked_index(lock
, 1);
669 clean
= merge_recursive(&o
, lookup_commit(head
),
670 remoteheads
->item
, reversed
, &result
);
671 if (active_cache_changed
&&
672 (write_cache(index_fd
, active_cache
, active_nr
) ||
673 commit_locked_index(lock
)))
674 die ("unable to write %s", get_index_file());
675 rollback_lock_file(lock
);
676 return clean
? 0 : 1;
678 return try_merge_command(strategy
, common
, head_arg
, remoteheads
);
682 static void count_diff_files(struct diff_queue_struct
*q
,
683 struct diff_options
*opt
, void *data
)
690 static int count_unmerged_entries(void)
694 for (i
= 0; i
< active_nr
; i
++)
695 if (ce_stage(active_cache
[i
]))
701 int checkout_fast_forward(const unsigned char *head
, const unsigned char *remote
)
703 struct tree
*trees
[MAX_UNPACK_TREES
];
704 struct unpack_trees_options opts
;
705 struct tree_desc t
[MAX_UNPACK_TREES
];
706 int i
, fd
, nr_trees
= 0;
707 struct dir_struct dir
;
708 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
710 refresh_cache(REFRESH_QUIET
);
712 fd
= hold_locked_index(lock_file
, 1);
714 memset(&trees
, 0, sizeof(trees
));
715 memset(&opts
, 0, sizeof(opts
));
716 memset(&t
, 0, sizeof(t
));
717 memset(&dir
, 0, sizeof(dir
));
718 dir
.flags
|= DIR_SHOW_IGNORED
;
719 dir
.exclude_per_dir
= ".gitignore";
723 opts
.src_index
= &the_index
;
724 opts
.dst_index
= &the_index
;
726 opts
.verbose_update
= 1;
728 opts
.fn
= twoway_merge
;
729 setup_unpack_trees_porcelain(&opts
, "merge");
731 trees
[nr_trees
] = parse_tree_indirect(head
);
732 if (!trees
[nr_trees
++])
734 trees
[nr_trees
] = parse_tree_indirect(remote
);
735 if (!trees
[nr_trees
++])
737 for (i
= 0; i
< nr_trees
; i
++) {
738 parse_tree(trees
[i
]);
739 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
741 if (unpack_trees(nr_trees
, t
, &opts
))
743 if (write_cache(fd
, active_cache
, active_nr
) ||
744 commit_locked_index(lock_file
))
745 die("unable to write new index file");
749 static void split_merge_strategies(const char *string
, struct strategy
**list
,
757 buf
= xstrdup(string
);
762 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
763 (*list
)[(*nr
)++].name
= xstrdup(q
);
768 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
769 (*list
)[(*nr
)++].name
= xstrdup(q
);
775 static void add_strategies(const char *string
, unsigned attr
)
777 struct strategy
*list
= NULL
;
778 int list_alloc
= 0, list_nr
= 0, i
;
780 memset(&list
, 0, sizeof(list
));
781 split_merge_strategies(string
, &list
, &list_nr
, &list_alloc
);
783 for (i
= 0; i
< list_nr
; i
++)
784 append_strategy(get_strategy(list
[i
].name
));
787 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
788 if (all_strategy
[i
].attr
& attr
)
789 append_strategy(&all_strategy
[i
]);
793 static int merge_trivial(void)
795 unsigned char result_tree
[20], result_commit
[20];
796 struct commit_list
*parent
= xmalloc(sizeof(*parent
));
798 write_tree_trivial(result_tree
);
799 printf("Wonderful.\n");
800 parent
->item
= lookup_commit(head
);
801 parent
->next
= xmalloc(sizeof(*parent
->next
));
802 parent
->next
->item
= remoteheads
->item
;
803 parent
->next
->next
= NULL
;
804 commit_tree(merge_msg
.buf
, result_tree
, parent
, result_commit
, NULL
);
805 finish(result_commit
, "In-index merge");
810 static int finish_automerge(struct commit_list
*common
,
811 unsigned char *result_tree
,
812 const char *wt_strategy
)
814 struct commit_list
*parents
= NULL
, *j
;
815 struct strbuf buf
= STRBUF_INIT
;
816 unsigned char result_commit
[20];
818 free_commit_list(common
);
819 if (allow_fast_forward
) {
820 parents
= remoteheads
;
821 commit_list_insert(lookup_commit(head
), &parents
);
822 parents
= reduce_heads(parents
);
824 struct commit_list
**pptr
= &parents
;
826 pptr
= &commit_list_insert(lookup_commit(head
),
828 for (j
= remoteheads
; j
; j
= j
->next
)
829 pptr
= &commit_list_insert(j
->item
, pptr
)->next
;
831 free_commit_list(remoteheads
);
832 strbuf_addch(&merge_msg
, '\n');
833 commit_tree(merge_msg
.buf
, result_tree
, parents
, result_commit
, NULL
);
834 strbuf_addf(&buf
, "Merge made by %s.", wt_strategy
);
835 finish(result_commit
, buf
.buf
);
836 strbuf_release(&buf
);
841 static int suggest_conflicts(int renormalizing
)
846 fp
= fopen(git_path("MERGE_MSG"), "a");
848 die_errno("Could not open '%s' for writing",
849 git_path("MERGE_MSG"));
850 fprintf(fp
, "\nConflicts:\n");
851 for (pos
= 0; pos
< active_nr
; pos
++) {
852 struct cache_entry
*ce
= active_cache
[pos
];
855 fprintf(fp
, "\t%s\n", ce
->name
);
856 while (pos
+ 1 < active_nr
&&
858 active_cache
[pos
+ 1]->name
))
863 rerere(allow_rerere_auto
);
864 printf("Automatic merge failed; "
865 "fix conflicts and then commit the result.\n");
869 static struct commit
*is_old_style_invocation(int argc
, const char **argv
)
871 struct commit
*second_token
= NULL
;
873 unsigned char second_sha1
[20];
875 if (get_sha1(argv
[1], second_sha1
))
877 second_token
= lookup_commit_reference_gently(second_sha1
, 0);
879 die("'%s' is not a commit", argv
[1]);
880 if (hashcmp(second_token
->object
.sha1
, head
))
886 static int evaluate_result(void)
891 /* Check how many files differ. */
892 init_revisions(&rev
, "");
893 setup_revisions(0, NULL
, &rev
, NULL
);
894 rev
.diffopt
.output_format
|=
895 DIFF_FORMAT_CALLBACK
;
896 rev
.diffopt
.format_callback
= count_diff_files
;
897 rev
.diffopt
.format_callback_data
= &cnt
;
898 run_diff_files(&rev
, 0);
901 * Check how many unmerged entries are
904 cnt
+= count_unmerged_entries();
909 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
911 unsigned char result_tree
[20];
912 struct strbuf buf
= STRBUF_INIT
;
913 const char *head_arg
;
914 int flag
, head_invalid
= 0, i
;
915 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
916 struct commit_list
*common
= NULL
;
917 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
918 struct commit_list
**remotes
= &remoteheads
;
920 if (read_cache_unmerged()) {
921 die_resolve_conflict("merge");
923 if (file_exists(git_path("MERGE_HEAD"))) {
925 * There is no unmerged entry, don't advise 'git
926 * add/rm <file>', just 'git commit'.
928 if (advice_resolve_conflict
)
929 die("You have not concluded your merge (MERGE_HEAD exists).\n"
930 "Please, commit your changes before you can merge.");
932 die("You have not concluded your merge (MERGE_HEAD exists).");
935 resolve_undo_clear();
937 * Check if we are _not_ on a detached HEAD, i.e. if there is a
940 branch
= resolve_ref("HEAD", head
, 0, &flag
);
941 if (branch
&& !prefixcmp(branch
, "refs/heads/"))
943 if (is_null_sha1(head
))
946 git_config(git_merge_config
, NULL
);
949 if (diff_use_color_default
== -1)
950 diff_use_color_default
= git_use_color_default
;
952 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
953 builtin_merge_usage
, 0);
958 if (!allow_fast_forward
)
959 die("You cannot combine --squash with --no-ff.");
963 if (!allow_fast_forward
&& fast_forward_only
)
964 die("You cannot combine --no-ff with --ff-only.");
967 usage_with_options(builtin_merge_usage
,
968 builtin_merge_options
);
971 * This could be traditional "merge <msg> HEAD <commit>..." and
972 * the way we can tell it is to see if the second token is HEAD,
973 * but some people might have misused the interface and used a
974 * committish that is the same as HEAD there instead.
975 * Traditional format never would have "-m" so it is an
976 * additional safety measure to check for it.
979 if (!have_message
&& is_old_style_invocation(argc
, argv
)) {
980 strbuf_addstr(&merge_msg
, argv
[0]);
984 } else if (head_invalid
) {
985 struct object
*remote_head
;
987 * If the merged head is a valid one there is no reason
988 * to forbid "git merge" into a branch yet to be born.
989 * We do the same for "git pull".
992 die("Can merge only exactly one commit into "
995 die("Squash commit into empty head not supported yet");
996 if (!allow_fast_forward
)
997 die("Non-fast-forward commit does not make sense into "
999 remote_head
= peel_to_type(argv
[0], 0, NULL
, OBJ_COMMIT
);
1001 die("%s - not something we can merge", argv
[0]);
1002 update_ref("initial pull", "HEAD", remote_head
->sha1
, NULL
, 0,
1004 reset_hard(remote_head
->sha1
, 0);
1007 struct strbuf merge_names
= STRBUF_INIT
;
1009 /* We are invoked directly as the first-class UI. */
1013 * All the rest are the commits being merged;
1014 * prepare the standard merge summary message to
1015 * be appended to the given message. If remote
1016 * is invalid we will die later in the common
1017 * codepath so we discard the error in this
1020 for (i
= 0; i
< argc
; i
++)
1021 merge_name(argv
[i
], &merge_names
);
1023 if (!have_message
|| shortlog_len
) {
1024 fmt_merge_msg(&merge_names
, &merge_msg
, !have_message
,
1027 strbuf_setlen(&merge_msg
, merge_msg
.len
- 1);
1031 if (head_invalid
|| !argc
)
1032 usage_with_options(builtin_merge_usage
,
1033 builtin_merge_options
);
1035 strbuf_addstr(&buf
, "merge");
1036 for (i
= 0; i
< argc
; i
++)
1037 strbuf_addf(&buf
, " %s", argv
[i
]);
1038 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
1041 for (i
= 0; i
< argc
; i
++) {
1043 struct commit
*commit
;
1045 o
= peel_to_type(argv
[i
], 0, NULL
, OBJ_COMMIT
);
1047 die("%s - not something we can merge", argv
[i
]);
1048 commit
= lookup_commit(o
->sha1
);
1049 commit
->util
= (void *)argv
[i
];
1050 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1052 strbuf_addf(&buf
, "GITHEAD_%s", sha1_to_hex(o
->sha1
));
1053 setenv(buf
.buf
, argv
[i
], 1);
1057 if (!use_strategies
) {
1058 if (!remoteheads
->next
)
1059 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
1061 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
1064 for (i
= 0; i
< use_strategies_nr
; i
++) {
1065 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
1066 allow_fast_forward
= 0;
1067 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
1071 if (!remoteheads
->next
)
1072 common
= get_merge_bases(lookup_commit(head
),
1073 remoteheads
->item
, 1);
1075 struct commit_list
*list
= remoteheads
;
1076 commit_list_insert(lookup_commit(head
), &list
);
1077 common
= get_octopus_merge_bases(list
);
1081 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head
, NULL
, 0,
1085 ; /* No common ancestors found. We need a real merge. */
1086 else if (!remoteheads
->next
&& !common
->next
&&
1087 common
->item
== remoteheads
->item
) {
1089 * If head can reach all the merge then we are up to date.
1090 * but first the most common case of merging one remote.
1092 finish_up_to_date("Already up-to-date.");
1094 } else if (allow_fast_forward
&& !remoteheads
->next
&&
1096 !hashcmp(common
->item
->object
.sha1
, head
)) {
1097 /* Again the most common case of merging one remote. */
1098 struct strbuf msg
= STRBUF_INIT
;
1102 strcpy(hex
, find_unique_abbrev(head
, DEFAULT_ABBREV
));
1105 printf("Updating %s..%s\n",
1107 find_unique_abbrev(remoteheads
->item
->object
.sha1
,
1109 strbuf_addstr(&msg
, "Fast-forward");
1112 " (no commit created; -m option ignored)");
1113 o
= peel_to_type(sha1_to_hex(remoteheads
->item
->object
.sha1
),
1114 0, NULL
, OBJ_COMMIT
);
1118 if (checkout_fast_forward(head
, remoteheads
->item
->object
.sha1
))
1121 finish(o
->sha1
, msg
.buf
);
1124 } else if (!remoteheads
->next
&& common
->next
)
1127 * We are not doing octopus and not fast-forward. Need
1130 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1132 * We are not doing octopus, not fast-forward, and have
1135 refresh_cache(REFRESH_QUIET
);
1136 if (allow_trivial
&& !fast_forward_only
) {
1137 /* See if it is really trivial. */
1138 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1139 printf("Trying really trivial in-index merge...\n");
1140 if (!read_tree_trivial(common
->item
->object
.sha1
,
1141 head
, remoteheads
->item
->object
.sha1
))
1142 return merge_trivial();
1147 * An octopus. If we can reach all the remote we are up
1151 struct commit_list
*j
;
1153 for (j
= remoteheads
; j
; j
= j
->next
) {
1154 struct commit_list
*common_one
;
1157 * Here we *have* to calculate the individual
1158 * merge_bases again, otherwise "git merge HEAD^
1159 * HEAD^^" would be missed.
1161 common_one
= get_merge_bases(lookup_commit(head
),
1163 if (hashcmp(common_one
->item
->object
.sha1
,
1164 j
->item
->object
.sha1
)) {
1170 finish_up_to_date("Already up-to-date. Yeeah!");
1175 if (fast_forward_only
)
1176 die("Not possible to fast-forward, aborting.");
1178 /* We are going to make a new commit. */
1179 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1182 * At this point, we need a real merge. No matter what strategy
1183 * we use, it would operate on the index, possibly affecting the
1184 * working tree, and when resolved cleanly, have the desired
1185 * tree in the index -- this means that the index must be in
1186 * sync with the head commit. The strategies are responsible
1189 if (use_strategies_nr
!= 1) {
1191 * Stash away the local changes so that we can try more
1196 memcpy(stash
, null_sha1
, 20);
1199 for (i
= 0; i
< use_strategies_nr
; i
++) {
1202 printf("Rewinding the tree to pristine...\n");
1205 if (use_strategies_nr
!= 1)
1206 printf("Trying merge strategy %s...\n",
1207 use_strategies
[i
]->name
);
1209 * Remember which strategy left the state in the working
1212 wt_strategy
= use_strategies
[i
]->name
;
1214 ret
= try_merge_strategy(use_strategies
[i
]->name
,
1216 if (!option_commit
&& !ret
) {
1219 * This is necessary here just to avoid writing
1220 * the tree, but later we will *not* exit with
1221 * status code 1 because merge_was_ok is set.
1228 * The backend exits with 1 when conflicts are
1229 * left to be resolved, with 2 when it does not
1230 * handle the given merge at all.
1233 int cnt
= evaluate_result();
1235 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1236 best_strategy
= use_strategies
[i
]->name
;
1246 /* Automerge succeeded. */
1247 write_tree_trivial(result_tree
);
1248 automerge_was_ok
= 1;
1253 * If we have a resulting tree, that means the strategy module
1254 * auto resolved the merge cleanly.
1256 if (automerge_was_ok
)
1257 return finish_automerge(common
, result_tree
, wt_strategy
);
1260 * Pick the result from the best strategy and have the user fix
1263 if (!best_strategy
) {
1265 if (use_strategies_nr
> 1)
1267 "No merge strategy handled the merge.\n");
1269 fprintf(stderr
, "Merge with strategy %s failed.\n",
1270 use_strategies
[0]->name
);
1272 } else if (best_strategy
== wt_strategy
)
1273 ; /* We already have its result in the working tree. */
1275 printf("Rewinding the tree to pristine...\n");
1277 printf("Using the %s to prepare resolving by hand.\n",
1279 try_merge_strategy(best_strategy
, common
, head_arg
);
1286 struct commit_list
*j
;
1288 for (j
= remoteheads
; j
; j
= j
->next
)
1289 strbuf_addf(&buf
, "%s\n",
1290 sha1_to_hex(j
->item
->object
.sha1
));
1291 fd
= open(git_path("MERGE_HEAD"), O_WRONLY
| O_CREAT
, 0666);
1293 die_errno("Could not open '%s' for writing",
1294 git_path("MERGE_HEAD"));
1295 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1296 die_errno("Could not write to '%s'", git_path("MERGE_HEAD"));
1298 strbuf_addch(&merge_msg
, '\n');
1299 fd
= open(git_path("MERGE_MSG"), O_WRONLY
| O_CREAT
, 0666);
1301 die_errno("Could not open '%s' for writing",
1302 git_path("MERGE_MSG"));
1303 if (write_in_full(fd
, merge_msg
.buf
, merge_msg
.len
) !=
1305 die_errno("Could not write to '%s'", git_path("MERGE_MSG"));
1307 fd
= open(git_path("MERGE_MODE"), O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
1309 die_errno("Could not open '%s' for writing",
1310 git_path("MERGE_MODE"));
1312 if (!allow_fast_forward
)
1313 strbuf_addf(&buf
, "no-ff");
1314 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1315 die_errno("Could not write to '%s'", git_path("MERGE_MODE"));
1320 fprintf(stderr
, "Automatic merge went well; "
1321 "stopped before committing as requested\n");
1324 return suggest_conflicts(option_renormalize
);