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
;
642 for (x
= 0; x
< xopts_nr
; x
++)
643 if (parse_merge_opt(&o
, xopts
[x
]))
644 die("Unknown option for merge-recursive: -X%s", xopts
[x
]);
646 o
.branch1
= head_arg
;
647 o
.branch2
= remoteheads
->item
->util
;
649 for (j
= common
; j
; j
= j
->next
)
650 commit_list_insert(j
->item
, &reversed
);
652 index_fd
= hold_locked_index(lock
, 1);
653 clean
= merge_recursive(&o
, lookup_commit(head
),
654 remoteheads
->item
, reversed
, &result
);
655 if (active_cache_changed
&&
656 (write_cache(index_fd
, active_cache
, active_nr
) ||
657 commit_locked_index(lock
)))
658 die ("unable to write %s", get_index_file());
659 rollback_lock_file(lock
);
660 return clean
? 0 : 1;
662 return try_merge_command(strategy
, common
, head_arg
, remoteheads
);
666 static void count_diff_files(struct diff_queue_struct
*q
,
667 struct diff_options
*opt
, void *data
)
674 static int count_unmerged_entries(void)
678 for (i
= 0; i
< active_nr
; i
++)
679 if (ce_stage(active_cache
[i
]))
685 int checkout_fast_forward(const unsigned char *head
, const unsigned char *remote
)
687 struct tree
*trees
[MAX_UNPACK_TREES
];
688 struct unpack_trees_options opts
;
689 struct tree_desc t
[MAX_UNPACK_TREES
];
690 int i
, fd
, nr_trees
= 0;
691 struct dir_struct dir
;
692 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
694 refresh_cache(REFRESH_QUIET
);
696 fd
= hold_locked_index(lock_file
, 1);
698 memset(&trees
, 0, sizeof(trees
));
699 memset(&opts
, 0, sizeof(opts
));
700 memset(&t
, 0, sizeof(t
));
701 memset(&dir
, 0, sizeof(dir
));
702 dir
.flags
|= DIR_SHOW_IGNORED
;
703 dir
.exclude_per_dir
= ".gitignore";
707 opts
.src_index
= &the_index
;
708 opts
.dst_index
= &the_index
;
710 opts
.verbose_update
= 1;
712 opts
.fn
= twoway_merge
;
713 setup_unpack_trees_porcelain(&opts
, "merge");
715 trees
[nr_trees
] = parse_tree_indirect(head
);
716 if (!trees
[nr_trees
++])
718 trees
[nr_trees
] = parse_tree_indirect(remote
);
719 if (!trees
[nr_trees
++])
721 for (i
= 0; i
< nr_trees
; i
++) {
722 parse_tree(trees
[i
]);
723 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
725 if (unpack_trees(nr_trees
, t
, &opts
))
727 if (write_cache(fd
, active_cache
, active_nr
) ||
728 commit_locked_index(lock_file
))
729 die("unable to write new index file");
733 static void split_merge_strategies(const char *string
, struct strategy
**list
,
741 buf
= xstrdup(string
);
746 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
747 (*list
)[(*nr
)++].name
= xstrdup(q
);
752 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
753 (*list
)[(*nr
)++].name
= xstrdup(q
);
759 static void add_strategies(const char *string
, unsigned attr
)
761 struct strategy
*list
= NULL
;
762 int list_alloc
= 0, list_nr
= 0, i
;
764 memset(&list
, 0, sizeof(list
));
765 split_merge_strategies(string
, &list
, &list_nr
, &list_alloc
);
767 for (i
= 0; i
< list_nr
; i
++)
768 append_strategy(get_strategy(list
[i
].name
));
771 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
772 if (all_strategy
[i
].attr
& attr
)
773 append_strategy(&all_strategy
[i
]);
777 static int merge_trivial(void)
779 unsigned char result_tree
[20], result_commit
[20];
780 struct commit_list
*parent
= xmalloc(sizeof(*parent
));
782 write_tree_trivial(result_tree
);
783 printf("Wonderful.\n");
784 parent
->item
= lookup_commit(head
);
785 parent
->next
= xmalloc(sizeof(*parent
->next
));
786 parent
->next
->item
= remoteheads
->item
;
787 parent
->next
->next
= NULL
;
788 commit_tree(merge_msg
.buf
, result_tree
, parent
, result_commit
, NULL
);
789 finish(result_commit
, "In-index merge");
794 static int finish_automerge(struct commit_list
*common
,
795 unsigned char *result_tree
,
796 const char *wt_strategy
)
798 struct commit_list
*parents
= NULL
, *j
;
799 struct strbuf buf
= STRBUF_INIT
;
800 unsigned char result_commit
[20];
802 free_commit_list(common
);
803 if (allow_fast_forward
) {
804 parents
= remoteheads
;
805 commit_list_insert(lookup_commit(head
), &parents
);
806 parents
= reduce_heads(parents
);
808 struct commit_list
**pptr
= &parents
;
810 pptr
= &commit_list_insert(lookup_commit(head
),
812 for (j
= remoteheads
; j
; j
= j
->next
)
813 pptr
= &commit_list_insert(j
->item
, pptr
)->next
;
815 free_commit_list(remoteheads
);
816 strbuf_addch(&merge_msg
, '\n');
817 commit_tree(merge_msg
.buf
, result_tree
, parents
, result_commit
, NULL
);
818 strbuf_addf(&buf
, "Merge made by %s.", wt_strategy
);
819 finish(result_commit
, buf
.buf
);
820 strbuf_release(&buf
);
825 static int suggest_conflicts(int renormalizing
)
830 fp
= fopen(git_path("MERGE_MSG"), "a");
832 die_errno("Could not open '%s' for writing",
833 git_path("MERGE_MSG"));
834 fprintf(fp
, "\nConflicts:\n");
835 for (pos
= 0; pos
< active_nr
; pos
++) {
836 struct cache_entry
*ce
= active_cache
[pos
];
839 fprintf(fp
, "\t%s\n", ce
->name
);
840 while (pos
+ 1 < active_nr
&&
842 active_cache
[pos
+ 1]->name
))
847 rerere(allow_rerere_auto
);
848 printf("Automatic merge failed; "
849 "fix conflicts and then commit the result.\n");
853 static struct commit
*is_old_style_invocation(int argc
, const char **argv
)
855 struct commit
*second_token
= NULL
;
857 unsigned char second_sha1
[20];
859 if (get_sha1(argv
[1], second_sha1
))
861 second_token
= lookup_commit_reference_gently(second_sha1
, 0);
863 die("'%s' is not a commit", argv
[1]);
864 if (hashcmp(second_token
->object
.sha1
, head
))
870 static int evaluate_result(void)
875 /* Check how many files differ. */
876 init_revisions(&rev
, "");
877 setup_revisions(0, NULL
, &rev
, NULL
);
878 rev
.diffopt
.output_format
|=
879 DIFF_FORMAT_CALLBACK
;
880 rev
.diffopt
.format_callback
= count_diff_files
;
881 rev
.diffopt
.format_callback_data
= &cnt
;
882 run_diff_files(&rev
, 0);
885 * Check how many unmerged entries are
888 cnt
+= count_unmerged_entries();
893 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
895 unsigned char result_tree
[20];
896 struct strbuf buf
= STRBUF_INIT
;
897 const char *head_arg
;
898 int flag
, head_invalid
= 0, i
;
899 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
900 struct commit_list
*common
= NULL
;
901 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
902 struct commit_list
**remotes
= &remoteheads
;
904 if (read_cache_unmerged()) {
905 die_resolve_conflict("merge");
907 if (file_exists(git_path("MERGE_HEAD"))) {
909 * There is no unmerged entry, don't advise 'git
910 * add/rm <file>', just 'git commit'.
912 if (advice_resolve_conflict
)
913 die("You have not concluded your merge (MERGE_HEAD exists).\n"
914 "Please, commit your changes before you can merge.");
916 die("You have not concluded your merge (MERGE_HEAD exists).");
919 resolve_undo_clear();
921 * Check if we are _not_ on a detached HEAD, i.e. if there is a
924 branch
= resolve_ref("HEAD", head
, 0, &flag
);
925 if (branch
&& !prefixcmp(branch
, "refs/heads/"))
927 if (is_null_sha1(head
))
930 git_config(git_merge_config
, NULL
);
933 if (diff_use_color_default
== -1)
934 diff_use_color_default
= git_use_color_default
;
936 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
937 builtin_merge_usage
, 0);
942 if (!allow_fast_forward
)
943 die("You cannot combine --squash with --no-ff.");
947 if (!allow_fast_forward
&& fast_forward_only
)
948 die("You cannot combine --no-ff with --ff-only.");
951 usage_with_options(builtin_merge_usage
,
952 builtin_merge_options
);
955 * This could be traditional "merge <msg> HEAD <commit>..." and
956 * the way we can tell it is to see if the second token is HEAD,
957 * but some people might have misused the interface and used a
958 * committish that is the same as HEAD there instead.
959 * Traditional format never would have "-m" so it is an
960 * additional safety measure to check for it.
963 if (!have_message
&& is_old_style_invocation(argc
, argv
)) {
964 strbuf_addstr(&merge_msg
, argv
[0]);
968 } else if (head_invalid
) {
969 struct object
*remote_head
;
971 * If the merged head is a valid one there is no reason
972 * to forbid "git merge" into a branch yet to be born.
973 * We do the same for "git pull".
976 die("Can merge only exactly one commit into "
979 die("Squash commit into empty head not supported yet");
980 if (!allow_fast_forward
)
981 die("Non-fast-forward commit does not make sense into "
983 remote_head
= peel_to_type(argv
[0], 0, NULL
, OBJ_COMMIT
);
985 die("%s - not something we can merge", argv
[0]);
986 update_ref("initial pull", "HEAD", remote_head
->sha1
, NULL
, 0,
988 reset_hard(remote_head
->sha1
, 0);
991 struct strbuf merge_names
= STRBUF_INIT
;
993 /* We are invoked directly as the first-class UI. */
997 * All the rest are the commits being merged;
998 * prepare the standard merge summary message to
999 * be appended to the given message. If remote
1000 * is invalid we will die later in the common
1001 * codepath so we discard the error in this
1004 for (i
= 0; i
< argc
; i
++)
1005 merge_name(argv
[i
], &merge_names
);
1007 if (!have_message
|| shortlog_len
) {
1008 fmt_merge_msg(&merge_names
, &merge_msg
, !have_message
,
1011 strbuf_setlen(&merge_msg
, merge_msg
.len
- 1);
1015 if (head_invalid
|| !argc
)
1016 usage_with_options(builtin_merge_usage
,
1017 builtin_merge_options
);
1019 strbuf_addstr(&buf
, "merge");
1020 for (i
= 0; i
< argc
; i
++)
1021 strbuf_addf(&buf
, " %s", argv
[i
]);
1022 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
1025 for (i
= 0; i
< argc
; i
++) {
1027 struct commit
*commit
;
1029 o
= peel_to_type(argv
[i
], 0, NULL
, OBJ_COMMIT
);
1031 die("%s - not something we can merge", argv
[i
]);
1032 commit
= lookup_commit(o
->sha1
);
1033 commit
->util
= (void *)argv
[i
];
1034 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1036 strbuf_addf(&buf
, "GITHEAD_%s", sha1_to_hex(o
->sha1
));
1037 setenv(buf
.buf
, argv
[i
], 1);
1041 if (!use_strategies
) {
1042 if (!remoteheads
->next
)
1043 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
1045 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
1048 for (i
= 0; i
< use_strategies_nr
; i
++) {
1049 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
1050 allow_fast_forward
= 0;
1051 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
1055 if (!remoteheads
->next
)
1056 common
= get_merge_bases(lookup_commit(head
),
1057 remoteheads
->item
, 1);
1059 struct commit_list
*list
= remoteheads
;
1060 commit_list_insert(lookup_commit(head
), &list
);
1061 common
= get_octopus_merge_bases(list
);
1065 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head
, NULL
, 0,
1069 ; /* No common ancestors found. We need a real merge. */
1070 else if (!remoteheads
->next
&& !common
->next
&&
1071 common
->item
== remoteheads
->item
) {
1073 * If head can reach all the merge then we are up to date.
1074 * but first the most common case of merging one remote.
1076 finish_up_to_date("Already up-to-date.");
1078 } else if (allow_fast_forward
&& !remoteheads
->next
&&
1080 !hashcmp(common
->item
->object
.sha1
, head
)) {
1081 /* Again the most common case of merging one remote. */
1082 struct strbuf msg
= STRBUF_INIT
;
1086 strcpy(hex
, find_unique_abbrev(head
, DEFAULT_ABBREV
));
1089 printf("Updating %s..%s\n",
1091 find_unique_abbrev(remoteheads
->item
->object
.sha1
,
1093 strbuf_addstr(&msg
, "Fast-forward");
1096 " (no commit created; -m option ignored)");
1097 o
= peel_to_type(sha1_to_hex(remoteheads
->item
->object
.sha1
),
1098 0, NULL
, OBJ_COMMIT
);
1102 if (checkout_fast_forward(head
, remoteheads
->item
->object
.sha1
))
1105 finish(o
->sha1
, msg
.buf
);
1108 } else if (!remoteheads
->next
&& common
->next
)
1111 * We are not doing octopus and not fast-forward. Need
1114 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1116 * We are not doing octopus, not fast-forward, and have
1119 refresh_cache(REFRESH_QUIET
);
1120 if (allow_trivial
&& !fast_forward_only
) {
1121 /* See if it is really trivial. */
1122 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1123 printf("Trying really trivial in-index merge...\n");
1124 if (!read_tree_trivial(common
->item
->object
.sha1
,
1125 head
, remoteheads
->item
->object
.sha1
))
1126 return merge_trivial();
1131 * An octopus. If we can reach all the remote we are up
1135 struct commit_list
*j
;
1137 for (j
= remoteheads
; j
; j
= j
->next
) {
1138 struct commit_list
*common_one
;
1141 * Here we *have* to calculate the individual
1142 * merge_bases again, otherwise "git merge HEAD^
1143 * HEAD^^" would be missed.
1145 common_one
= get_merge_bases(lookup_commit(head
),
1147 if (hashcmp(common_one
->item
->object
.sha1
,
1148 j
->item
->object
.sha1
)) {
1154 finish_up_to_date("Already up-to-date. Yeeah!");
1159 if (fast_forward_only
)
1160 die("Not possible to fast-forward, aborting.");
1162 /* We are going to make a new commit. */
1163 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1166 * At this point, we need a real merge. No matter what strategy
1167 * we use, it would operate on the index, possibly affecting the
1168 * working tree, and when resolved cleanly, have the desired
1169 * tree in the index -- this means that the index must be in
1170 * sync with the head commit. The strategies are responsible
1173 if (use_strategies_nr
!= 1) {
1175 * Stash away the local changes so that we can try more
1180 memcpy(stash
, null_sha1
, 20);
1183 for (i
= 0; i
< use_strategies_nr
; i
++) {
1186 printf("Rewinding the tree to pristine...\n");
1189 if (use_strategies_nr
!= 1)
1190 printf("Trying merge strategy %s...\n",
1191 use_strategies
[i
]->name
);
1193 * Remember which strategy left the state in the working
1196 wt_strategy
= use_strategies
[i
]->name
;
1198 ret
= try_merge_strategy(use_strategies
[i
]->name
,
1200 if (!option_commit
&& !ret
) {
1203 * This is necessary here just to avoid writing
1204 * the tree, but later we will *not* exit with
1205 * status code 1 because merge_was_ok is set.
1212 * The backend exits with 1 when conflicts are
1213 * left to be resolved, with 2 when it does not
1214 * handle the given merge at all.
1217 int cnt
= evaluate_result();
1219 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1220 best_strategy
= use_strategies
[i
]->name
;
1230 /* Automerge succeeded. */
1231 write_tree_trivial(result_tree
);
1232 automerge_was_ok
= 1;
1237 * If we have a resulting tree, that means the strategy module
1238 * auto resolved the merge cleanly.
1240 if (automerge_was_ok
)
1241 return finish_automerge(common
, result_tree
, wt_strategy
);
1244 * Pick the result from the best strategy and have the user fix
1247 if (!best_strategy
) {
1249 if (use_strategies_nr
> 1)
1251 "No merge strategy handled the merge.\n");
1253 fprintf(stderr
, "Merge with strategy %s failed.\n",
1254 use_strategies
[0]->name
);
1256 } else if (best_strategy
== wt_strategy
)
1257 ; /* We already have its result in the working tree. */
1259 printf("Rewinding the tree to pristine...\n");
1261 printf("Using the %s to prepare resolving by hand.\n",
1263 try_merge_strategy(best_strategy
, common
, head_arg
);
1270 struct commit_list
*j
;
1272 for (j
= remoteheads
; j
; j
= j
->next
)
1273 strbuf_addf(&buf
, "%s\n",
1274 sha1_to_hex(j
->item
->object
.sha1
));
1275 fd
= open(git_path("MERGE_HEAD"), O_WRONLY
| O_CREAT
, 0666);
1277 die_errno("Could not open '%s' for writing",
1278 git_path("MERGE_HEAD"));
1279 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1280 die_errno("Could not write to '%s'", git_path("MERGE_HEAD"));
1282 strbuf_addch(&merge_msg
, '\n');
1283 fd
= open(git_path("MERGE_MSG"), O_WRONLY
| O_CREAT
, 0666);
1285 die_errno("Could not open '%s' for writing",
1286 git_path("MERGE_MSG"));
1287 if (write_in_full(fd
, merge_msg
.buf
, merge_msg
.len
) !=
1289 die_errno("Could not write to '%s'", git_path("MERGE_MSG"));
1291 fd
= open(git_path("MERGE_MODE"), O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
1293 die_errno("Could not open '%s' for writing",
1294 git_path("MERGE_MODE"));
1296 if (!allow_fast_forward
)
1297 strbuf_addf(&buf
, "no-ff");
1298 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1299 die_errno("Could not write to '%s'", git_path("MERGE_MODE"));
1304 fprintf(stderr
, "Automatic merge went well; "
1305 "stopped before committing as requested\n");
1308 return suggest_conflicts(option_renormalize
);