4 * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
6 * Based on git-merge.sh by Junio C Hamano.
10 #include "parse-options.h"
12 #include "run-command.h"
18 #include "unpack-trees.h"
19 #include "cache-tree.h"
26 #include "merge-recursive.h"
27 #include "resolve-undo.h"
29 #define DEFAULT_TWOHEAD (1<<0)
30 #define DEFAULT_OCTOPUS (1<<1)
31 #define NO_FAST_FORWARD (1<<2)
32 #define NO_TRIVIAL (1<<3)
39 static const char * const builtin_merge_usage
[] = {
40 "git merge [options] <remote>...",
41 "git merge [options] <msg> HEAD <remote>",
45 static int show_diffstat
= 1, option_log
, squash
;
46 static int option_commit
= 1, allow_fast_forward
= 1;
47 static int fast_forward_only
;
48 static int allow_trivial
= 1, have_message
;
49 static struct strbuf merge_msg
;
50 static struct commit_list
*remoteheads
;
51 static unsigned char head
[20], stash
[20];
52 static struct strategy
**use_strategies
;
53 static size_t use_strategies_nr
, use_strategies_alloc
;
54 static const char **xopts
;
55 static size_t xopts_nr
, xopts_alloc
;
56 static const char *branch
;
57 static int option_renormalize
;
59 static int allow_rerere_auto
;
61 static struct strategy all_strategy
[] = {
62 { "recursive", DEFAULT_TWOHEAD
| NO_TRIVIAL
},
63 { "octopus", DEFAULT_OCTOPUS
},
65 { "ours", NO_FAST_FORWARD
| NO_TRIVIAL
},
66 { "subtree", NO_FAST_FORWARD
| NO_TRIVIAL
},
69 static const char *pull_twohead
, *pull_octopus
;
71 static int option_parse_message(const struct option
*opt
,
72 const char *arg
, int unset
)
74 struct strbuf
*buf
= opt
->value
;
77 strbuf_setlen(buf
, 0);
79 strbuf_addf(buf
, "%s%s", buf
->len
? "\n\n" : "", arg
);
82 return error("switch `m' requires a value");
86 static struct strategy
*get_strategy(const char *name
)
90 static struct cmdnames main_cmds
, other_cmds
;
96 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
97 if (!strcmp(name
, all_strategy
[i
].name
))
98 return &all_strategy
[i
];
101 struct cmdnames not_strategies
;
104 memset(¬_strategies
, 0, sizeof(struct cmdnames
));
105 load_command_list("git-merge-", &main_cmds
, &other_cmds
);
106 for (i
= 0; i
< main_cmds
.cnt
; i
++) {
108 struct cmdname
*ent
= main_cmds
.names
[i
];
109 for (j
= 0; j
< ARRAY_SIZE(all_strategy
); j
++)
110 if (!strncmp(ent
->name
, all_strategy
[j
].name
, ent
->len
)
111 && !all_strategy
[j
].name
[ent
->len
])
114 add_cmdname(¬_strategies
, ent
->name
, ent
->len
);
116 exclude_cmds(&main_cmds
, ¬_strategies
);
118 if (!is_in_cmdlist(&main_cmds
, name
) && !is_in_cmdlist(&other_cmds
, name
)) {
119 fprintf(stderr
, "Could not find merge strategy '%s'.\n", name
);
120 fprintf(stderr
, "Available strategies are:");
121 for (i
= 0; i
< main_cmds
.cnt
; i
++)
122 fprintf(stderr
, " %s", main_cmds
.names
[i
]->name
);
123 fprintf(stderr
, ".\n");
124 if (other_cmds
.cnt
) {
125 fprintf(stderr
, "Available custom strategies are:");
126 for (i
= 0; i
< other_cmds
.cnt
; i
++)
127 fprintf(stderr
, " %s", other_cmds
.names
[i
]->name
);
128 fprintf(stderr
, ".\n");
133 ret
= xcalloc(1, sizeof(struct strategy
));
134 ret
->name
= xstrdup(name
);
135 ret
->attr
= NO_TRIVIAL
;
139 static void append_strategy(struct strategy
*s
)
141 ALLOC_GROW(use_strategies
, use_strategies_nr
+ 1, use_strategies_alloc
);
142 use_strategies
[use_strategies_nr
++] = s
;
145 static int option_parse_strategy(const struct option
*opt
,
146 const char *name
, int unset
)
151 append_strategy(get_strategy(name
));
155 static int option_parse_x(const struct option
*opt
,
156 const char *arg
, int unset
)
161 ALLOC_GROW(xopts
, xopts_nr
+ 1, xopts_alloc
);
162 xopts
[xopts_nr
++] = xstrdup(arg
);
166 static int option_parse_n(const struct option
*opt
,
167 const char *arg
, int unset
)
169 show_diffstat
= unset
;
173 static struct option builtin_merge_options
[] = {
174 { OPTION_CALLBACK
, 'n', NULL
, NULL
, NULL
,
175 "do not show a diffstat at the end of the merge",
176 PARSE_OPT_NOARG
, option_parse_n
},
177 OPT_BOOLEAN(0, "stat", &show_diffstat
,
178 "show a diffstat at the end of the merge"),
179 OPT_BOOLEAN(0, "summary", &show_diffstat
, "(synonym to --stat)"),
180 OPT_BOOLEAN(0, "log", &option_log
,
181 "add list of one-line log to merge commit message"),
182 OPT_BOOLEAN(0, "squash", &squash
,
183 "create a single commit instead of doing a merge"),
184 OPT_BOOLEAN(0, "commit", &option_commit
,
185 "perform a commit if the merge succeeds (default)"),
186 OPT_BOOLEAN(0, "ff", &allow_fast_forward
,
187 "allow fast-forward (default)"),
188 OPT_BOOLEAN(0, "ff-only", &fast_forward_only
,
189 "abort if fast-forward is not possible"),
190 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto
),
191 OPT_CALLBACK('s', "strategy", &use_strategies
, "strategy",
192 "merge strategy to use", option_parse_strategy
),
193 OPT_CALLBACK('X', "strategy-option", &xopts
, "option=value",
194 "option for selected merge strategy", option_parse_x
),
195 OPT_CALLBACK('m', "message", &merge_msg
, "message",
196 "message to be used for the merge commit (if any)",
197 option_parse_message
),
198 OPT__VERBOSITY(&verbosity
),
202 /* Cleans up metadata that is uninteresting after a succeeded merge. */
203 static void drop_save(void)
205 unlink(git_path("MERGE_HEAD"));
206 unlink(git_path("MERGE_MSG"));
207 unlink(git_path("MERGE_MODE"));
210 static void save_state(void)
213 struct child_process cp
;
214 struct strbuf buffer
= STRBUF_INIT
;
215 const char *argv
[] = {"stash", "create", NULL
};
217 memset(&cp
, 0, sizeof(cp
));
222 if (start_command(&cp
))
223 die("could not run stash.");
224 len
= strbuf_read(&buffer
, cp
.out
, 1024);
227 if (finish_command(&cp
) || len
< 0)
231 strbuf_setlen(&buffer
, buffer
.len
-1);
232 if (get_sha1(buffer
.buf
, stash
))
233 die("not a valid object: %s", buffer
.buf
);
236 static void reset_hard(unsigned const char *sha1
, int verbose
)
241 args
[i
++] = "read-tree";
244 args
[i
++] = "--reset";
246 args
[i
++] = sha1_to_hex(sha1
);
249 if (run_command_v_opt(args
, RUN_GIT_CMD
))
250 die("read-tree failed");
253 static void restore_state(void)
255 struct strbuf sb
= STRBUF_INIT
;
256 const char *args
[] = { "stash", "apply", NULL
, NULL
};
258 if (is_null_sha1(stash
))
263 args
[2] = sha1_to_hex(stash
);
266 * It is OK to ignore error here, for example when there was
267 * nothing to restore.
269 run_command_v_opt(args
, RUN_GIT_CMD
);
272 refresh_cache(REFRESH_QUIET
);
275 /* This is called when no merge was necessary. */
276 static void finish_up_to_date(const char *msg
)
279 printf("%s%s\n", squash
? " (nothing to squash)" : "", msg
);
283 static void squash_message(void)
286 struct commit
*commit
;
287 struct strbuf out
= STRBUF_INIT
;
288 struct commit_list
*j
;
290 struct pretty_print_context ctx
= {0};
292 printf("Squash commit -- not updating HEAD\n");
293 fd
= open(git_path("SQUASH_MSG"), O_WRONLY
| O_CREAT
, 0666);
295 die_errno("Could not write to '%s'", git_path("SQUASH_MSG"));
297 init_revisions(&rev
, NULL
);
298 rev
.ignore_merges
= 1;
299 rev
.commit_format
= CMIT_FMT_MEDIUM
;
301 commit
= lookup_commit(head
);
302 commit
->object
.flags
|= UNINTERESTING
;
303 add_pending_object(&rev
, &commit
->object
, NULL
);
305 for (j
= remoteheads
; j
; j
= j
->next
)
306 add_pending_object(&rev
, &j
->item
->object
, NULL
);
308 setup_revisions(0, NULL
, &rev
, NULL
);
309 if (prepare_revision_walk(&rev
))
310 die("revision walk setup failed");
312 ctx
.abbrev
= rev
.abbrev
;
313 ctx
.date_mode
= rev
.date_mode
;
315 strbuf_addstr(&out
, "Squashed commit of the following:\n");
316 while ((commit
= get_revision(&rev
)) != NULL
) {
317 strbuf_addch(&out
, '\n');
318 strbuf_addf(&out
, "commit %s\n",
319 sha1_to_hex(commit
->object
.sha1
));
320 pretty_print_commit(rev
.commit_format
, commit
, &out
, &ctx
);
322 if (write(fd
, out
.buf
, out
.len
) < 0)
323 die_errno("Writing SQUASH_MSG");
325 die_errno("Finishing SQUASH_MSG");
326 strbuf_release(&out
);
329 static void finish(const unsigned char *new_head
, const char *msg
)
331 struct strbuf reflog_message
= STRBUF_INIT
;
334 strbuf_addstr(&reflog_message
, getenv("GIT_REFLOG_ACTION"));
338 strbuf_addf(&reflog_message
, "%s: %s",
339 getenv("GIT_REFLOG_ACTION"), msg
);
344 if (verbosity
>= 0 && !merge_msg
.len
)
345 printf("No merge message -- not updating HEAD\n");
347 const char *argv_gc_auto
[] = { "gc", "--auto", NULL
};
348 update_ref(reflog_message
.buf
, "HEAD",
352 * We ignore errors in 'gc --auto', since the
353 * user should see them.
355 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
358 if (new_head
&& show_diffstat
) {
359 struct diff_options opts
;
361 opts
.output_format
|=
362 DIFF_FORMAT_SUMMARY
| DIFF_FORMAT_DIFFSTAT
;
363 opts
.detect_rename
= DIFF_DETECT_RENAME
;
364 if (diff_use_color_default
> 0)
365 DIFF_OPT_SET(&opts
, COLOR_DIFF
);
366 if (diff_setup_done(&opts
) < 0)
367 die("diff_setup_done failed");
368 diff_tree_sha1(head
, new_head
, "", &opts
);
373 /* Run a post-merge hook */
374 run_hook(NULL
, "post-merge", squash
? "1" : "0", NULL
);
376 strbuf_release(&reflog_message
);
379 /* Get the name for the merge commit's message. */
380 static void merge_name(const char *remote
, struct strbuf
*msg
)
382 struct object
*remote_head
;
383 unsigned char branch_head
[20], buf_sha
[20];
384 struct strbuf buf
= STRBUF_INIT
;
385 struct strbuf bname
= STRBUF_INIT
;
390 strbuf_branchname(&bname
, remote
);
393 memset(branch_head
, 0, sizeof(branch_head
));
394 remote_head
= peel_to_type(remote
, 0, NULL
, OBJ_COMMIT
);
396 die("'%s' does not point to a commit", remote
);
398 if (dwim_ref(remote
, strlen(remote
), branch_head
, &found_ref
) > 0) {
399 if (!prefixcmp(found_ref
, "refs/heads/")) {
400 strbuf_addf(msg
, "%s\t\tbranch '%s' of .\n",
401 sha1_to_hex(branch_head
), remote
);
404 if (!prefixcmp(found_ref
, "refs/remotes/")) {
405 strbuf_addf(msg
, "%s\t\tremote branch '%s' of .\n",
406 sha1_to_hex(branch_head
), remote
);
411 /* See if remote matches <name>^^^.. or <name>~<number> */
412 for (len
= 0, ptr
= remote
+ strlen(remote
);
413 remote
< ptr
&& ptr
[-1] == '^';
420 ptr
= strrchr(remote
, '~');
422 int seen_nonzero
= 0;
425 while (*++ptr
&& isdigit(*ptr
)) {
426 seen_nonzero
|= (*ptr
!= '0');
430 len
= 0; /* not ...~<number> */
431 else if (seen_nonzero
)
434 early
= 1; /* "name~" is "name~1"! */
438 struct strbuf truname
= STRBUF_INIT
;
439 strbuf_addstr(&truname
, "refs/heads/");
440 strbuf_addstr(&truname
, remote
);
441 strbuf_setlen(&truname
, truname
.len
- len
);
442 if (resolve_ref(truname
.buf
, buf_sha
, 1, NULL
)) {
444 "%s\t\tbranch '%s'%s of .\n",
445 sha1_to_hex(remote_head
->sha1
),
447 (early
? " (early part)" : ""));
448 strbuf_release(&truname
);
453 if (!strcmp(remote
, "FETCH_HEAD") &&
454 !access(git_path("FETCH_HEAD"), R_OK
)) {
456 struct strbuf line
= STRBUF_INIT
;
459 fp
= fopen(git_path("FETCH_HEAD"), "r");
461 die_errno("could not open '%s' for reading",
462 git_path("FETCH_HEAD"));
463 strbuf_getline(&line
, fp
, '\n');
465 ptr
= strstr(line
.buf
, "\tnot-for-merge\t");
467 strbuf_remove(&line
, ptr
-line
.buf
+1, 13);
468 strbuf_addbuf(msg
, &line
);
469 strbuf_release(&line
);
472 strbuf_addf(msg
, "%s\t\tcommit '%s'\n",
473 sha1_to_hex(remote_head
->sha1
), remote
);
475 strbuf_release(&buf
);
476 strbuf_release(&bname
);
479 static int git_merge_config(const char *k
, const char *v
, void *cb
)
481 if (branch
&& !prefixcmp(k
, "branch.") &&
482 !prefixcmp(k
+ 7, branch
) &&
483 !strcmp(k
+ 7 + strlen(branch
), ".mergeoptions")) {
489 argc
= split_cmdline(buf
, &argv
);
491 die("Bad branch.%s.mergeoptions string: %s", branch
,
492 split_cmdline_strerror(argc
));
493 argv
= xrealloc(argv
, sizeof(*argv
) * (argc
+ 2));
494 memmove(argv
+ 1, argv
, sizeof(*argv
) * (argc
+ 1));
496 parse_options(argc
, argv
, NULL
, builtin_merge_options
,
497 builtin_merge_usage
, 0);
501 if (!strcmp(k
, "merge.diffstat") || !strcmp(k
, "merge.stat"))
502 show_diffstat
= git_config_bool(k
, v
);
503 else if (!strcmp(k
, "pull.twohead"))
504 return git_config_string(&pull_twohead
, k
, v
);
505 else if (!strcmp(k
, "pull.octopus"))
506 return git_config_string(&pull_octopus
, k
, v
);
507 else if (!strcmp(k
, "merge.log") || !strcmp(k
, "merge.summary"))
508 option_log
= git_config_bool(k
, v
);
509 else if (!strcmp(k
, "merge.renormalize"))
510 option_renormalize
= git_config_bool(k
, v
);
511 return git_diff_ui_config(k
, v
, cb
);
514 static int read_tree_trivial(unsigned char *common
, unsigned char *head
,
518 struct tree
*trees
[MAX_UNPACK_TREES
];
519 struct tree_desc t
[MAX_UNPACK_TREES
];
520 struct unpack_trees_options opts
;
522 memset(&opts
, 0, sizeof(opts
));
524 opts
.src_index
= &the_index
;
525 opts
.dst_index
= &the_index
;
527 opts
.verbose_update
= 1;
528 opts
.trivial_merges_only
= 1;
530 trees
[nr_trees
] = parse_tree_indirect(common
);
531 if (!trees
[nr_trees
++])
533 trees
[nr_trees
] = parse_tree_indirect(head
);
534 if (!trees
[nr_trees
++])
536 trees
[nr_trees
] = parse_tree_indirect(one
);
537 if (!trees
[nr_trees
++])
539 opts
.fn
= threeway_merge
;
540 cache_tree_free(&active_cache_tree
);
541 for (i
= 0; i
< nr_trees
; i
++) {
542 parse_tree(trees
[i
]);
543 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
545 if (unpack_trees(nr_trees
, t
, &opts
))
550 static void write_tree_trivial(unsigned char *sha1
)
552 if (write_cache_as_tree(sha1
, 0, NULL
))
553 die("git write-tree failed to write a tree");
556 int try_merge_command(const char *strategy
, struct commit_list
*common
,
557 const char *head_arg
, struct commit_list
*remotes
)
560 int i
= 0, x
= 0, ret
;
561 struct commit_list
*j
;
562 struct strbuf buf
= STRBUF_INIT
;
564 args
= xmalloc((4 + xopts_nr
+ commit_list_count(common
) +
565 commit_list_count(remotes
)) * sizeof(char *));
566 strbuf_addf(&buf
, "merge-%s", strategy
);
568 for (x
= 0; x
< xopts_nr
; x
++) {
569 char *s
= xmalloc(strlen(xopts
[x
])+2+1);
571 strcpy(s
+2, xopts
[x
]);
574 for (j
= common
; j
; j
= j
->next
)
575 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
577 args
[i
++] = head_arg
;
578 for (j
= remotes
; j
; j
= j
->next
)
579 args
[i
++] = xstrdup(sha1_to_hex(j
->item
->object
.sha1
));
581 ret
= run_command_v_opt(args
, RUN_GIT_CMD
);
582 strbuf_release(&buf
);
584 for (x
= 0; x
< xopts_nr
; x
++)
585 free((void *)args
[i
++]);
586 for (j
= common
; j
; j
= j
->next
)
587 free((void *)args
[i
++]);
589 for (j
= remotes
; j
; j
= j
->next
)
590 free((void *)args
[i
++]);
593 if (read_cache() < 0)
594 die("failed to read the cache");
595 resolve_undo_clear();
600 static int try_merge_strategy(const char *strategy
, struct commit_list
*common
,
601 const char *head_arg
)
604 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
606 index_fd
= hold_locked_index(lock
, 1);
607 refresh_cache(REFRESH_QUIET
);
608 if (active_cache_changed
&&
609 (write_cache(index_fd
, active_cache
, active_nr
) ||
610 commit_locked_index(lock
)))
611 return error("Unable to write index.");
612 rollback_lock_file(lock
);
614 if (!strcmp(strategy
, "recursive") || !strcmp(strategy
, "subtree")) {
616 struct commit
*result
;
617 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
619 struct commit_list
*reversed
= NULL
;
620 struct merge_options o
;
621 struct commit_list
*j
;
623 if (remoteheads
->next
) {
624 error("Not handling anything other than two heads merge.");
628 init_merge_options(&o
);
629 if (!strcmp(strategy
, "subtree"))
630 o
.subtree_shift
= "";
632 o
.renormalize
= option_renormalize
;
635 * NEEDSWORK: merge with table in builtin/merge-recursive
637 for (x
= 0; x
< xopts_nr
; x
++) {
638 if (!strcmp(xopts
[x
], "ours"))
639 o
.recursive_variant
= MERGE_RECURSIVE_OURS
;
640 else if (!strcmp(xopts
[x
], "theirs"))
641 o
.recursive_variant
= MERGE_RECURSIVE_THEIRS
;
642 else if (!strcmp(xopts
[x
], "subtree"))
643 o
.subtree_shift
= "";
644 else if (!prefixcmp(xopts
[x
], "subtree="))
645 o
.subtree_shift
= xopts
[x
]+8;
646 else if (!strcmp(xopts
[x
], "renormalize"))
648 else if (!strcmp(xopts
[x
], "no-renormalize"))
651 die("Unknown option for merge-recursive: -X%s", xopts
[x
]);
654 o
.branch1
= head_arg
;
655 o
.branch2
= remoteheads
->item
->util
;
657 for (j
= common
; j
; j
= j
->next
)
658 commit_list_insert(j
->item
, &reversed
);
660 index_fd
= hold_locked_index(lock
, 1);
661 clean
= merge_recursive(&o
, lookup_commit(head
),
662 remoteheads
->item
, reversed
, &result
);
663 if (active_cache_changed
&&
664 (write_cache(index_fd
, active_cache
, active_nr
) ||
665 commit_locked_index(lock
)))
666 die ("unable to write %s", get_index_file());
667 rollback_lock_file(lock
);
668 return clean
? 0 : 1;
670 return try_merge_command(strategy
, common
, head_arg
, remoteheads
);
674 static void count_diff_files(struct diff_queue_struct
*q
,
675 struct diff_options
*opt
, void *data
)
682 static int count_unmerged_entries(void)
686 for (i
= 0; i
< active_nr
; i
++)
687 if (ce_stage(active_cache
[i
]))
693 int checkout_fast_forward(const unsigned char *head
, const unsigned char *remote
)
695 struct tree
*trees
[MAX_UNPACK_TREES
];
696 struct unpack_trees_options opts
;
697 struct tree_desc t
[MAX_UNPACK_TREES
];
698 int i
, fd
, nr_trees
= 0;
699 struct dir_struct dir
;
700 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
702 refresh_cache(REFRESH_QUIET
);
704 fd
= hold_locked_index(lock_file
, 1);
706 memset(&trees
, 0, sizeof(trees
));
707 memset(&opts
, 0, sizeof(opts
));
708 memset(&t
, 0, sizeof(t
));
709 memset(&dir
, 0, sizeof(dir
));
710 dir
.flags
|= DIR_SHOW_IGNORED
;
711 dir
.exclude_per_dir
= ".gitignore";
715 opts
.src_index
= &the_index
;
716 opts
.dst_index
= &the_index
;
718 opts
.verbose_update
= 1;
720 opts
.fn
= twoway_merge
;
721 opts
.show_all_errors
= 1;
722 set_porcelain_error_msgs(opts
.msgs
, "merge");
724 trees
[nr_trees
] = parse_tree_indirect(head
);
725 if (!trees
[nr_trees
++])
727 trees
[nr_trees
] = parse_tree_indirect(remote
);
728 if (!trees
[nr_trees
++])
730 for (i
= 0; i
< nr_trees
; i
++) {
731 parse_tree(trees
[i
]);
732 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
734 if (unpack_trees(nr_trees
, t
, &opts
))
736 if (write_cache(fd
, active_cache
, active_nr
) ||
737 commit_locked_index(lock_file
))
738 die("unable to write new index file");
742 static void split_merge_strategies(const char *string
, struct strategy
**list
,
750 buf
= xstrdup(string
);
755 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
756 (*list
)[(*nr
)++].name
= xstrdup(q
);
761 ALLOC_GROW(*list
, *nr
+ 1, *alloc
);
762 (*list
)[(*nr
)++].name
= xstrdup(q
);
768 static void add_strategies(const char *string
, unsigned attr
)
770 struct strategy
*list
= NULL
;
771 int list_alloc
= 0, list_nr
= 0, i
;
773 memset(&list
, 0, sizeof(list
));
774 split_merge_strategies(string
, &list
, &list_nr
, &list_alloc
);
776 for (i
= 0; i
< list_nr
; i
++)
777 append_strategy(get_strategy(list
[i
].name
));
780 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
781 if (all_strategy
[i
].attr
& attr
)
782 append_strategy(&all_strategy
[i
]);
786 static int merge_trivial(void)
788 unsigned char result_tree
[20], result_commit
[20];
789 struct commit_list
*parent
= xmalloc(sizeof(*parent
));
791 write_tree_trivial(result_tree
);
792 printf("Wonderful.\n");
793 parent
->item
= lookup_commit(head
);
794 parent
->next
= xmalloc(sizeof(*parent
->next
));
795 parent
->next
->item
= remoteheads
->item
;
796 parent
->next
->next
= NULL
;
797 commit_tree(merge_msg
.buf
, result_tree
, parent
, result_commit
, NULL
);
798 finish(result_commit
, "In-index merge");
803 static int finish_automerge(struct commit_list
*common
,
804 unsigned char *result_tree
,
805 const char *wt_strategy
)
807 struct commit_list
*parents
= NULL
, *j
;
808 struct strbuf buf
= STRBUF_INIT
;
809 unsigned char result_commit
[20];
811 free_commit_list(common
);
812 if (allow_fast_forward
) {
813 parents
= remoteheads
;
814 commit_list_insert(lookup_commit(head
), &parents
);
815 parents
= reduce_heads(parents
);
817 struct commit_list
**pptr
= &parents
;
819 pptr
= &commit_list_insert(lookup_commit(head
),
821 for (j
= remoteheads
; j
; j
= j
->next
)
822 pptr
= &commit_list_insert(j
->item
, pptr
)->next
;
824 free_commit_list(remoteheads
);
825 strbuf_addch(&merge_msg
, '\n');
826 commit_tree(merge_msg
.buf
, result_tree
, parents
, result_commit
, NULL
);
827 strbuf_addf(&buf
, "Merge made by %s.", wt_strategy
);
828 finish(result_commit
, buf
.buf
);
829 strbuf_release(&buf
);
834 static int suggest_conflicts(int renormalizing
)
839 fp
= fopen(git_path("MERGE_MSG"), "a");
841 die_errno("Could not open '%s' for writing",
842 git_path("MERGE_MSG"));
843 fprintf(fp
, "\nConflicts:\n");
844 for (pos
= 0; pos
< active_nr
; pos
++) {
845 struct cache_entry
*ce
= active_cache
[pos
];
848 fprintf(fp
, "\t%s\n", ce
->name
);
849 while (pos
+ 1 < active_nr
&&
851 active_cache
[pos
+ 1]->name
))
856 rerere(allow_rerere_auto
);
857 printf("Automatic merge failed; "
858 "fix conflicts and then commit the result.\n");
862 static struct commit
*is_old_style_invocation(int argc
, const char **argv
)
864 struct commit
*second_token
= NULL
;
866 unsigned char second_sha1
[20];
868 if (get_sha1(argv
[1], second_sha1
))
870 second_token
= lookup_commit_reference_gently(second_sha1
, 0);
872 die("'%s' is not a commit", argv
[1]);
873 if (hashcmp(second_token
->object
.sha1
, head
))
879 static int evaluate_result(void)
884 /* Check how many files differ. */
885 init_revisions(&rev
, "");
886 setup_revisions(0, NULL
, &rev
, NULL
);
887 rev
.diffopt
.output_format
|=
888 DIFF_FORMAT_CALLBACK
;
889 rev
.diffopt
.format_callback
= count_diff_files
;
890 rev
.diffopt
.format_callback_data
= &cnt
;
891 run_diff_files(&rev
, 0);
894 * Check how many unmerged entries are
897 cnt
+= count_unmerged_entries();
902 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
904 unsigned char result_tree
[20];
905 struct strbuf buf
= STRBUF_INIT
;
906 const char *head_arg
;
907 int flag
, head_invalid
= 0, i
;
908 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
909 struct commit_list
*common
= NULL
;
910 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
911 struct commit_list
**remotes
= &remoteheads
;
913 if (read_cache_unmerged()) {
914 die_resolve_conflict("merge");
916 if (file_exists(git_path("MERGE_HEAD"))) {
918 * There is no unmerged entry, don't advise 'git
919 * add/rm <file>', just 'git commit'.
921 if (advice_resolve_conflict
)
922 die("You have not concluded your merge (MERGE_HEAD exists).\n"
923 "Please, commit your changes before you can merge.");
925 die("You have not concluded your merge (MERGE_HEAD exists).");
928 resolve_undo_clear();
930 * Check if we are _not_ on a detached HEAD, i.e. if there is a
933 branch
= resolve_ref("HEAD", head
, 0, &flag
);
934 if (branch
&& !prefixcmp(branch
, "refs/heads/"))
936 if (is_null_sha1(head
))
939 git_config(git_merge_config
, NULL
);
942 if (diff_use_color_default
== -1)
943 diff_use_color_default
= git_use_color_default
;
945 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
946 builtin_merge_usage
, 0);
951 if (!allow_fast_forward
)
952 die("You cannot combine --squash with --no-ff.");
956 if (!allow_fast_forward
&& fast_forward_only
)
957 die("You cannot combine --no-ff with --ff-only.");
960 usage_with_options(builtin_merge_usage
,
961 builtin_merge_options
);
964 * This could be traditional "merge <msg> HEAD <commit>..." and
965 * the way we can tell it is to see if the second token is HEAD,
966 * but some people might have misused the interface and used a
967 * committish that is the same as HEAD there instead.
968 * Traditional format never would have "-m" so it is an
969 * additional safety measure to check for it.
972 if (!have_message
&& is_old_style_invocation(argc
, argv
)) {
973 strbuf_addstr(&merge_msg
, argv
[0]);
977 } else if (head_invalid
) {
978 struct object
*remote_head
;
980 * If the merged head is a valid one there is no reason
981 * to forbid "git merge" into a branch yet to be born.
982 * We do the same for "git pull".
985 die("Can merge only exactly one commit into "
988 die("Squash commit into empty head not supported yet");
989 if (!allow_fast_forward
)
990 die("Non-fast-forward commit does not make sense into "
992 remote_head
= peel_to_type(argv
[0], 0, NULL
, OBJ_COMMIT
);
994 die("%s - not something we can merge", argv
[0]);
995 update_ref("initial pull", "HEAD", remote_head
->sha1
, NULL
, 0,
997 reset_hard(remote_head
->sha1
, 0);
1000 struct strbuf merge_names
= STRBUF_INIT
;
1002 /* We are invoked directly as the first-class UI. */
1006 * All the rest are the commits being merged;
1007 * prepare the standard merge summary message to
1008 * be appended to the given message. If remote
1009 * is invalid we will die later in the common
1010 * codepath so we discard the error in this
1013 for (i
= 0; i
< argc
; i
++)
1014 merge_name(argv
[i
], &merge_names
);
1016 if (have_message
&& option_log
)
1017 fmt_merge_msg_shortlog(&merge_names
, &merge_msg
);
1018 else if (!have_message
)
1019 fmt_merge_msg(option_log
, &merge_names
, &merge_msg
);
1022 if (!(have_message
&& !option_log
) && merge_msg
.len
)
1023 strbuf_setlen(&merge_msg
, merge_msg
.len
-1);
1026 if (head_invalid
|| !argc
)
1027 usage_with_options(builtin_merge_usage
,
1028 builtin_merge_options
);
1030 strbuf_addstr(&buf
, "merge");
1031 for (i
= 0; i
< argc
; i
++)
1032 strbuf_addf(&buf
, " %s", argv
[i
]);
1033 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
1036 for (i
= 0; i
< argc
; i
++) {
1038 struct commit
*commit
;
1040 o
= peel_to_type(argv
[i
], 0, NULL
, OBJ_COMMIT
);
1042 die("%s - not something we can merge", argv
[i
]);
1043 commit
= lookup_commit(o
->sha1
);
1044 commit
->util
= (void *)argv
[i
];
1045 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1047 strbuf_addf(&buf
, "GITHEAD_%s", sha1_to_hex(o
->sha1
));
1048 setenv(buf
.buf
, argv
[i
], 1);
1052 if (!use_strategies
) {
1053 if (!remoteheads
->next
)
1054 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
1056 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
1059 for (i
= 0; i
< use_strategies_nr
; i
++) {
1060 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
1061 allow_fast_forward
= 0;
1062 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
1066 if (!remoteheads
->next
)
1067 common
= get_merge_bases(lookup_commit(head
),
1068 remoteheads
->item
, 1);
1070 struct commit_list
*list
= remoteheads
;
1071 commit_list_insert(lookup_commit(head
), &list
);
1072 common
= get_octopus_merge_bases(list
);
1076 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head
, NULL
, 0,
1080 ; /* No common ancestors found. We need a real merge. */
1081 else if (!remoteheads
->next
&& !common
->next
&&
1082 common
->item
== remoteheads
->item
) {
1084 * If head can reach all the merge then we are up to date.
1085 * but first the most common case of merging one remote.
1087 finish_up_to_date("Already up-to-date.");
1089 } else if (allow_fast_forward
&& !remoteheads
->next
&&
1091 !hashcmp(common
->item
->object
.sha1
, head
)) {
1092 /* Again the most common case of merging one remote. */
1093 struct strbuf msg
= STRBUF_INIT
;
1097 strcpy(hex
, find_unique_abbrev(head
, DEFAULT_ABBREV
));
1100 printf("Updating %s..%s\n",
1102 find_unique_abbrev(remoteheads
->item
->object
.sha1
,
1104 strbuf_addstr(&msg
, "Fast-forward");
1107 " (no commit created; -m option ignored)");
1108 o
= peel_to_type(sha1_to_hex(remoteheads
->item
->object
.sha1
),
1109 0, NULL
, OBJ_COMMIT
);
1113 if (checkout_fast_forward(head
, remoteheads
->item
->object
.sha1
))
1116 finish(o
->sha1
, msg
.buf
);
1119 } else if (!remoteheads
->next
&& common
->next
)
1122 * We are not doing octopus and not fast-forward. Need
1125 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1127 * We are not doing octopus, not fast-forward, and have
1130 refresh_cache(REFRESH_QUIET
);
1131 if (allow_trivial
&& !fast_forward_only
) {
1132 /* See if it is really trivial. */
1133 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1134 printf("Trying really trivial in-index merge...\n");
1135 if (!read_tree_trivial(common
->item
->object
.sha1
,
1136 head
, remoteheads
->item
->object
.sha1
))
1137 return merge_trivial();
1142 * An octopus. If we can reach all the remote we are up
1146 struct commit_list
*j
;
1148 for (j
= remoteheads
; j
; j
= j
->next
) {
1149 struct commit_list
*common_one
;
1152 * Here we *have* to calculate the individual
1153 * merge_bases again, otherwise "git merge HEAD^
1154 * HEAD^^" would be missed.
1156 common_one
= get_merge_bases(lookup_commit(head
),
1158 if (hashcmp(common_one
->item
->object
.sha1
,
1159 j
->item
->object
.sha1
)) {
1165 finish_up_to_date("Already up-to-date. Yeeah!");
1170 if (fast_forward_only
)
1171 die("Not possible to fast-forward, aborting.");
1173 /* We are going to make a new commit. */
1174 git_committer_info(IDENT_ERROR_ON_NO_NAME
);
1177 * At this point, we need a real merge. No matter what strategy
1178 * we use, it would operate on the index, possibly affecting the
1179 * working tree, and when resolved cleanly, have the desired
1180 * tree in the index -- this means that the index must be in
1181 * sync with the head commit. The strategies are responsible
1184 if (use_strategies_nr
!= 1) {
1186 * Stash away the local changes so that we can try more
1191 memcpy(stash
, null_sha1
, 20);
1194 for (i
= 0; i
< use_strategies_nr
; i
++) {
1197 printf("Rewinding the tree to pristine...\n");
1200 if (use_strategies_nr
!= 1)
1201 printf("Trying merge strategy %s...\n",
1202 use_strategies
[i
]->name
);
1204 * Remember which strategy left the state in the working
1207 wt_strategy
= use_strategies
[i
]->name
;
1209 ret
= try_merge_strategy(use_strategies
[i
]->name
,
1211 if (!option_commit
&& !ret
) {
1214 * This is necessary here just to avoid writing
1215 * the tree, but later we will *not* exit with
1216 * status code 1 because merge_was_ok is set.
1223 * The backend exits with 1 when conflicts are
1224 * left to be resolved, with 2 when it does not
1225 * handle the given merge at all.
1228 int cnt
= evaluate_result();
1230 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1231 best_strategy
= use_strategies
[i
]->name
;
1241 /* Automerge succeeded. */
1242 write_tree_trivial(result_tree
);
1243 automerge_was_ok
= 1;
1248 * If we have a resulting tree, that means the strategy module
1249 * auto resolved the merge cleanly.
1251 if (automerge_was_ok
)
1252 return finish_automerge(common
, result_tree
, wt_strategy
);
1255 * Pick the result from the best strategy and have the user fix
1258 if (!best_strategy
) {
1260 if (use_strategies_nr
> 1)
1262 "No merge strategy handled the merge.\n");
1264 fprintf(stderr
, "Merge with strategy %s failed.\n",
1265 use_strategies
[0]->name
);
1267 } else if (best_strategy
== wt_strategy
)
1268 ; /* We already have its result in the working tree. */
1270 printf("Rewinding the tree to pristine...\n");
1272 printf("Using the %s to prepare resolving by hand.\n",
1274 try_merge_strategy(best_strategy
, common
, head_arg
);
1281 struct commit_list
*j
;
1283 for (j
= remoteheads
; j
; j
= j
->next
)
1284 strbuf_addf(&buf
, "%s\n",
1285 sha1_to_hex(j
->item
->object
.sha1
));
1286 fd
= open(git_path("MERGE_HEAD"), O_WRONLY
| O_CREAT
, 0666);
1288 die_errno("Could not open '%s' for writing",
1289 git_path("MERGE_HEAD"));
1290 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1291 die_errno("Could not write to '%s'", git_path("MERGE_HEAD"));
1293 strbuf_addch(&merge_msg
, '\n');
1294 fd
= open(git_path("MERGE_MSG"), O_WRONLY
| O_CREAT
, 0666);
1296 die_errno("Could not open '%s' for writing",
1297 git_path("MERGE_MSG"));
1298 if (write_in_full(fd
, merge_msg
.buf
, merge_msg
.len
) !=
1300 die_errno("Could not write to '%s'", git_path("MERGE_MSG"));
1302 fd
= open(git_path("MERGE_MODE"), O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
1304 die_errno("Could not open '%s' for writing",
1305 git_path("MERGE_MODE"));
1307 if (!allow_fast_forward
)
1308 strbuf_addf(&buf
, "no-ff");
1309 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
)
1310 die_errno("Could not write to '%s'", git_path("MERGE_MODE"));
1315 fprintf(stderr
, "Automatic merge went well; "
1316 "stopped before committing as requested\n");
1319 return suggest_conflicts(option_renormalize
);