Coverage Report

Created: 2024-09-08 06:24

/src/git/builtin/merge.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Builtin "git merge"
3
 *
4
 * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
5
 *
6
 * Based on git-merge.sh by Junio C Hamano.
7
 */
8
9
#include "builtin.h"
10
#include "abspath.h"
11
#include "advice.h"
12
#include "config.h"
13
#include "editor.h"
14
#include "environment.h"
15
#include "gettext.h"
16
#include "hex.h"
17
#include "object-name.h"
18
#include "parse-options.h"
19
#include "lockfile.h"
20
#include "run-command.h"
21
#include "hook.h"
22
#include "diff.h"
23
#include "diff-merges.h"
24
#include "refs.h"
25
#include "refspec.h"
26
#include "commit.h"
27
#include "diffcore.h"
28
#include "path.h"
29
#include "revision.h"
30
#include "unpack-trees.h"
31
#include "cache-tree.h"
32
#include "dir.h"
33
#include "color.h"
34
#include "rerere.h"
35
#include "help.h"
36
#include "merge.h"
37
#include "merge-recursive.h"
38
#include "merge-ort-wrappers.h"
39
#include "resolve-undo.h"
40
#include "remote.h"
41
#include "fmt-merge-msg.h"
42
#include "sequencer.h"
43
#include "string-list.h"
44
#include "tag.h"
45
#include "alias.h"
46
#include "branch.h"
47
#include "commit-reach.h"
48
#include "wt-status.h"
49
#include "commit-graph.h"
50
51
0
#define DEFAULT_TWOHEAD (1<<0)
52
0
#define DEFAULT_OCTOPUS (1<<1)
53
0
#define NO_FAST_FORWARD (1<<2)
54
0
#define NO_TRIVIAL      (1<<3)
55
56
struct strategy {
57
  const char *name;
58
  unsigned attr;
59
};
60
61
static const char * const builtin_merge_usage[] = {
62
  N_("git merge [<options>] [<commit>...]"),
63
  "git merge --abort",
64
  "git merge --continue",
65
  NULL
66
};
67
68
static int show_diffstat = 1, shortlog_len = -1, squash;
69
static int option_commit = -1;
70
static int option_edit = -1;
71
static int allow_trivial = 1, have_message, verify_signatures;
72
static int check_trust_level = 1;
73
static int overwrite_ignore = 1;
74
static struct strbuf merge_msg = STRBUF_INIT;
75
static struct strategy **use_strategies;
76
static size_t use_strategies_nr, use_strategies_alloc;
77
static struct strvec xopts = STRVEC_INIT;
78
static const char *branch;
79
static char *branch_mergeoptions;
80
static int verbosity;
81
static int allow_rerere_auto;
82
static int abort_current_merge;
83
static int quit_current_merge;
84
static int continue_current_merge;
85
static int allow_unrelated_histories;
86
static int show_progress = -1;
87
static int default_to_upstream = 1;
88
static int signoff;
89
static const char *sign_commit;
90
static int autostash;
91
static int no_verify;
92
static char *into_name;
93
94
static struct strategy all_strategy[] = {
95
  { "recursive",  NO_TRIVIAL },
96
  { "octopus",    DEFAULT_OCTOPUS },
97
  { "ort",        DEFAULT_TWOHEAD | NO_TRIVIAL },
98
  { "resolve",    0 },
99
  { "ours",       NO_FAST_FORWARD | NO_TRIVIAL },
100
  { "subtree",    NO_FAST_FORWARD | NO_TRIVIAL },
101
};
102
103
static char *pull_twohead, *pull_octopus;
104
105
enum ff_type {
106
  FF_NO,
107
  FF_ALLOW,
108
  FF_ONLY
109
};
110
111
static enum ff_type fast_forward = FF_ALLOW;
112
113
static char *cleanup_arg;
114
static enum commit_msg_cleanup_mode cleanup_mode;
115
116
static int option_parse_message(const struct option *opt,
117
        const char *arg, int unset)
118
0
{
119
0
  struct strbuf *buf = opt->value;
120
121
0
  if (unset)
122
0
    strbuf_setlen(buf, 0);
123
0
  else if (arg) {
124
0
    strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
125
0
    have_message = 1;
126
0
  } else
127
0
    return error(_("switch `m' requires a value"));
128
0
  return 0;
129
0
}
130
131
static enum parse_opt_result option_read_message(struct parse_opt_ctx_t *ctx,
132
             const struct option *opt,
133
             const char *arg_not_used,
134
             int unset)
135
0
{
136
0
  struct strbuf *buf = opt->value;
137
0
  const char *arg;
138
139
0
  BUG_ON_OPT_ARG(arg_not_used);
140
0
  if (unset)
141
0
    BUG("-F cannot be negated");
142
143
0
  if (ctx->opt) {
144
0
    arg = ctx->opt;
145
0
    ctx->opt = NULL;
146
0
  } else if (ctx->argc > 1) {
147
0
    ctx->argc--;
148
0
    arg = *++ctx->argv;
149
0
  } else
150
0
    return error(_("option `%s' requires a value"), opt->long_name);
151
152
0
  if (buf->len)
153
0
    strbuf_addch(buf, '\n');
154
0
  if (ctx->prefix && !is_absolute_path(arg))
155
0
    arg = prefix_filename(ctx->prefix, arg);
156
0
  if (strbuf_read_file(buf, arg, 0) < 0)
157
0
    return error(_("could not read file '%s'"), arg);
158
0
  have_message = 1;
159
160
0
  return 0;
161
0
}
162
163
static struct strategy *get_strategy(const char *name)
164
0
{
165
0
  int i;
166
0
  struct strategy *ret;
167
0
  static struct cmdnames main_cmds = {0}, other_cmds = {0};
168
0
  static int loaded;
169
0
  char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
170
171
0
  if (!name)
172
0
    return NULL;
173
174
0
  if (default_strategy &&
175
0
      !strcmp(default_strategy, "ort") &&
176
0
      !strcmp(name, "recursive")) {
177
0
    name = "ort";
178
0
  }
179
180
0
  for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
181
0
    if (!strcmp(name, all_strategy[i].name))
182
0
      return &all_strategy[i];
183
184
0
  if (!loaded) {
185
0
    struct cmdnames not_strategies = {0};
186
0
    loaded = 1;
187
188
0
    load_command_list("git-merge-", &main_cmds, &other_cmds);
189
0
    for (i = 0; i < main_cmds.cnt; i++) {
190
0
      int j, found = 0;
191
0
      struct cmdname *ent = main_cmds.names[i];
192
0
      for (j = 0; !found && j < ARRAY_SIZE(all_strategy); j++)
193
0
        if (!xstrncmpz(all_strategy[j].name, ent->name, ent->len))
194
0
          found = 1;
195
0
      if (!found)
196
0
        add_cmdname(&not_strategies, ent->name, ent->len);
197
0
    }
198
0
    exclude_cmds(&main_cmds, &not_strategies);
199
200
0
    cmdnames_release(&not_strategies);
201
0
  }
202
0
  if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
203
0
    fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
204
0
    fprintf(stderr, _("Available strategies are:"));
205
0
    for (i = 0; i < main_cmds.cnt; i++)
206
0
      fprintf(stderr, " %s", main_cmds.names[i]->name);
207
0
    fprintf(stderr, ".\n");
208
0
    if (other_cmds.cnt) {
209
0
      fprintf(stderr, _("Available custom strategies are:"));
210
0
      for (i = 0; i < other_cmds.cnt; i++)
211
0
        fprintf(stderr, " %s", other_cmds.names[i]->name);
212
0
      fprintf(stderr, ".\n");
213
0
    }
214
0
    exit(1);
215
0
  }
216
217
0
  CALLOC_ARRAY(ret, 1);
218
0
  ret->name = xstrdup(name);
219
0
  ret->attr = NO_TRIVIAL;
220
221
0
  cmdnames_release(&main_cmds);
222
0
  cmdnames_release(&other_cmds);
223
0
  return ret;
224
0
}
225
226
static void append_strategy(struct strategy *s)
227
0
{
228
0
  ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
229
0
  use_strategies[use_strategies_nr++] = s;
230
0
}
231
232
static int option_parse_strategy(const struct option *opt UNUSED,
233
         const char *name, int unset)
234
0
{
235
0
  if (unset)
236
0
    return 0;
237
238
0
  append_strategy(get_strategy(name));
239
0
  return 0;
240
0
}
241
242
static struct option builtin_merge_options[] = {
243
  OPT_SET_INT('n', NULL, &show_diffstat,
244
    N_("do not show a diffstat at the end of the merge"), 0),
245
  OPT_BOOL(0, "stat", &show_diffstat,
246
    N_("show a diffstat at the end of the merge")),
247
  OPT_BOOL(0, "summary", &show_diffstat, N_("(synonym to --stat)")),
248
  { OPTION_INTEGER, 0, "log", &shortlog_len, N_("n"),
249
    N_("add (at most <n>) entries from shortlog to merge commit message"),
250
    PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
251
  OPT_BOOL(0, "squash", &squash,
252
    N_("create a single commit instead of doing a merge")),
253
  OPT_BOOL(0, "commit", &option_commit,
254
    N_("perform a commit if the merge succeeds (default)")),
255
  OPT_BOOL('e', "edit", &option_edit,
256
    N_("edit message before committing")),
257
  OPT_CLEANUP(&cleanup_arg),
258
  OPT_SET_INT(0, "ff", &fast_forward, N_("allow fast-forward (default)"), FF_ALLOW),
259
  OPT_SET_INT_F(0, "ff-only", &fast_forward,
260
          N_("abort if fast-forward is not possible"),
261
          FF_ONLY, PARSE_OPT_NONEG),
262
  OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
263
  OPT_BOOL(0, "verify-signatures", &verify_signatures,
264
    N_("verify that the named commit has a valid GPG signature")),
265
  OPT_CALLBACK('s', "strategy", NULL, N_("strategy"),
266
    N_("merge strategy to use"), option_parse_strategy),
267
  OPT_STRVEC('X', "strategy-option", &xopts, N_("option=value"),
268
    N_("option for selected merge strategy")),
269
  OPT_CALLBACK('m', "message", &merge_msg, N_("message"),
270
    N_("merge commit message (for a non-fast-forward merge)"),
271
    option_parse_message),
272
  { OPTION_LOWLEVEL_CALLBACK, 'F', "file", &merge_msg, N_("path"),
273
    N_("read message from file"), PARSE_OPT_NONEG,
274
    NULL, 0, option_read_message },
275
  OPT_STRING(0, "into-name", &into_name, N_("name"),
276
       N_("use <name> instead of the real target")),
277
  OPT__VERBOSITY(&verbosity),
278
  OPT_BOOL(0, "abort", &abort_current_merge,
279
    N_("abort the current in-progress merge")),
280
  OPT_BOOL(0, "quit", &quit_current_merge,
281
    N_("--abort but leave index and working tree alone")),
282
  OPT_BOOL(0, "continue", &continue_current_merge,
283
    N_("continue the current in-progress merge")),
284
  OPT_BOOL(0, "allow-unrelated-histories", &allow_unrelated_histories,
285
     N_("allow merging unrelated histories")),
286
  OPT_SET_INT(0, "progress", &show_progress, N_("force progress reporting"), 1),
287
  { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
288
    N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
289
  OPT_AUTOSTASH(&autostash),
290
  OPT_BOOL(0, "overwrite-ignore", &overwrite_ignore, N_("update ignored files (default)")),
291
  OPT_BOOL(0, "signoff", &signoff, N_("add a Signed-off-by trailer")),
292
  OPT_BOOL(0, "no-verify", &no_verify, N_("bypass pre-merge-commit and commit-msg hooks")),
293
  OPT_END()
294
};
295
296
static int save_state(struct object_id *stash)
297
0
{
298
0
  int len;
299
0
  struct child_process cp = CHILD_PROCESS_INIT;
300
0
  struct strbuf buffer = STRBUF_INIT;
301
0
  struct lock_file lock_file = LOCK_INIT;
302
0
  int fd;
303
0
  int rc = -1;
304
305
0
  fd = repo_hold_locked_index(the_repository, &lock_file, 0);
306
0
  refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
307
0
  if (0 <= fd)
308
0
    repo_update_index_if_able(the_repository, &lock_file);
309
0
  rollback_lock_file(&lock_file);
310
311
0
  strvec_pushl(&cp.args, "stash", "create", NULL);
312
0
  cp.out = -1;
313
0
  cp.git_cmd = 1;
314
315
0
  if (start_command(&cp))
316
0
    die(_("could not run stash."));
317
0
  len = strbuf_read(&buffer, cp.out, 1024);
318
0
  close(cp.out);
319
320
0
  if (finish_command(&cp) || len < 0)
321
0
    die(_("stash failed"));
322
0
  else if (!len)   /* no changes */
323
0
    goto out;
324
0
  strbuf_setlen(&buffer, buffer.len-1);
325
0
  if (repo_get_oid(the_repository, buffer.buf, stash))
326
0
    die(_("not a valid object: %s"), buffer.buf);
327
0
  rc = 0;
328
0
out:
329
0
  strbuf_release(&buffer);
330
0
  return rc;
331
0
}
332
333
static void read_empty(const struct object_id *oid)
334
0
{
335
0
  struct child_process cmd = CHILD_PROCESS_INIT;
336
337
0
  strvec_pushl(&cmd.args, "read-tree", "-m", "-u",
338
0
         empty_tree_oid_hex(the_repository->hash_algo),
339
0
         oid_to_hex(oid), NULL);
340
0
  cmd.git_cmd = 1;
341
342
0
  if (run_command(&cmd))
343
0
    die(_("read-tree failed"));
344
0
}
345
346
static void reset_hard(const struct object_id *oid)
347
0
{
348
0
  struct child_process cmd = CHILD_PROCESS_INIT;
349
350
0
  strvec_pushl(&cmd.args, "read-tree", "-v", "--reset", "-u",
351
0
         oid_to_hex(oid), NULL);
352
0
  cmd.git_cmd = 1;
353
354
0
  if (run_command(&cmd))
355
0
    die(_("read-tree failed"));
356
0
}
357
358
static void restore_state(const struct object_id *head,
359
        const struct object_id *stash)
360
0
{
361
0
  struct child_process cmd = CHILD_PROCESS_INIT;
362
363
0
  reset_hard(head);
364
365
0
  if (is_null_oid(stash))
366
0
    goto refresh_cache;
367
368
0
  strvec_pushl(&cmd.args, "stash", "apply", "--index", "--quiet", NULL);
369
0
  strvec_push(&cmd.args, oid_to_hex(stash));
370
371
  /*
372
   * It is OK to ignore error here, for example when there was
373
   * nothing to restore.
374
   */
375
0
  cmd.git_cmd = 1;
376
0
  run_command(&cmd);
377
378
0
refresh_cache:
379
0
  discard_index(the_repository->index);
380
0
  if (repo_read_index(the_repository) < 0)
381
0
    die(_("could not read index"));
382
0
}
383
384
/* This is called when no merge was necessary. */
385
static void finish_up_to_date(void)
386
0
{
387
0
  if (verbosity >= 0) {
388
0
    if (squash)
389
0
      puts(_("Already up to date. (nothing to squash)"));
390
0
    else
391
0
      puts(_("Already up to date."));
392
0
  }
393
0
  remove_merge_branch_state(the_repository);
394
0
}
395
396
static void squash_message(struct commit *commit, struct commit_list *remoteheads)
397
0
{
398
0
  struct rev_info rev;
399
0
  struct strbuf out = STRBUF_INIT;
400
0
  struct commit_list *j;
401
0
  struct pretty_print_context ctx = {0};
402
403
0
  printf(_("Squash commit -- not updating HEAD\n"));
404
405
0
  repo_init_revisions(the_repository, &rev, NULL);
406
0
  diff_merges_suppress(&rev);
407
0
  rev.commit_format = CMIT_FMT_MEDIUM;
408
409
0
  commit->object.flags |= UNINTERESTING;
410
0
  add_pending_object(&rev, &commit->object, NULL);
411
412
0
  for (j = remoteheads; j; j = j->next)
413
0
    add_pending_object(&rev, &j->item->object, NULL);
414
415
0
  setup_revisions(0, NULL, &rev, NULL);
416
0
  if (prepare_revision_walk(&rev))
417
0
    die(_("revision walk setup failed"));
418
419
0
  ctx.abbrev = rev.abbrev;
420
0
  ctx.date_mode = rev.date_mode;
421
0
  ctx.fmt = rev.commit_format;
422
423
0
  strbuf_addstr(&out, "Squashed commit of the following:\n");
424
0
  while ((commit = get_revision(&rev)) != NULL) {
425
0
    strbuf_addch(&out, '\n');
426
0
    strbuf_addf(&out, "commit %s\n",
427
0
      oid_to_hex(&commit->object.oid));
428
0
    pretty_print_commit(&ctx, commit, &out);
429
0
  }
430
0
  write_file_buf(git_path_squash_msg(the_repository), out.buf, out.len);
431
0
  strbuf_release(&out);
432
0
  release_revisions(&rev);
433
0
}
434
435
static void finish(struct commit *head_commit,
436
       struct commit_list *remoteheads,
437
       const struct object_id *new_head, const char *msg)
438
0
{
439
0
  struct strbuf reflog_message = STRBUF_INIT;
440
0
  const struct object_id *head = &head_commit->object.oid;
441
442
0
  if (!msg)
443
0
    strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
444
0
  else {
445
0
    if (verbosity >= 0)
446
0
      printf("%s\n", msg);
447
0
    strbuf_addf(&reflog_message, "%s: %s",
448
0
      getenv("GIT_REFLOG_ACTION"), msg);
449
0
  }
450
0
  if (squash) {
451
0
    squash_message(head_commit, remoteheads);
452
0
  } else {
453
0
    if (verbosity >= 0 && !merge_msg.len)
454
0
      printf(_("No merge message -- not updating HEAD\n"));
455
0
    else {
456
0
      refs_update_ref(get_main_ref_store(the_repository),
457
0
          reflog_message.buf, "HEAD", new_head,
458
0
          head,
459
0
          0, UPDATE_REFS_DIE_ON_ERR);
460
      /*
461
       * We ignore errors in 'gc --auto', since the
462
       * user should see them.
463
       */
464
0
      run_auto_maintenance(verbosity < 0);
465
0
    }
466
0
  }
467
0
  if (new_head && show_diffstat) {
468
0
    struct diff_options opts;
469
0
    repo_diff_setup(the_repository, &opts);
470
0
    init_diffstat_widths(&opts);
471
0
    opts.output_format |=
472
0
      DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
473
0
    opts.detect_rename = DIFF_DETECT_RENAME;
474
0
    diff_setup_done(&opts);
475
0
    diff_tree_oid(head, new_head, "", &opts);
476
0
    diffcore_std(&opts);
477
0
    diff_flush(&opts);
478
0
  }
479
480
  /* Run a post-merge hook */
481
0
  run_hooks_l(the_repository, "post-merge", squash ? "1" : "0", NULL);
482
483
0
  if (new_head)
484
0
    apply_autostash_ref(the_repository, "MERGE_AUTOSTASH");
485
0
  strbuf_release(&reflog_message);
486
0
}
487
488
/* Get the name for the merge commit's message. */
489
static void merge_name(const char *remote, struct strbuf *msg)
490
0
{
491
0
  struct commit *remote_head;
492
0
  struct object_id branch_head;
493
0
  struct strbuf bname = STRBUF_INIT;
494
0
  struct merge_remote_desc *desc;
495
0
  const char *ptr;
496
0
  char *found_ref = NULL;
497
0
  int len, early;
498
499
0
  strbuf_branchname(&bname, remote, 0);
500
0
  remote = bname.buf;
501
502
0
  oidclr(&branch_head, the_repository->hash_algo);
503
0
  remote_head = get_merge_parent(remote);
504
0
  if (!remote_head)
505
0
    die(_("'%s' does not point to a commit"), remote);
506
507
0
  if (repo_dwim_ref(the_repository, remote, strlen(remote), &branch_head,
508
0
        &found_ref, 0) > 0) {
509
0
    if (starts_with(found_ref, "refs/heads/")) {
510
0
      strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
511
0
            oid_to_hex(&branch_head), remote);
512
0
      goto cleanup;
513
0
    }
514
0
    if (starts_with(found_ref, "refs/tags/")) {
515
0
      strbuf_addf(msg, "%s\t\ttag '%s' of .\n",
516
0
            oid_to_hex(&branch_head), remote);
517
0
      goto cleanup;
518
0
    }
519
0
    if (starts_with(found_ref, "refs/remotes/")) {
520
0
      strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
521
0
            oid_to_hex(&branch_head), remote);
522
0
      goto cleanup;
523
0
    }
524
0
  }
525
526
  /* See if remote matches <name>^^^.. or <name>~<number> */
527
0
  for (len = 0, ptr = remote + strlen(remote);
528
0
       remote < ptr && ptr[-1] == '^';
529
0
       ptr--)
530
0
    len++;
531
0
  if (len)
532
0
    early = 1;
533
0
  else {
534
0
    early = 0;
535
0
    ptr = strrchr(remote, '~');
536
0
    if (ptr) {
537
0
      int seen_nonzero = 0;
538
539
0
      len++; /* count ~ */
540
0
      while (*++ptr && isdigit(*ptr)) {
541
0
        seen_nonzero |= (*ptr != '0');
542
0
        len++;
543
0
      }
544
0
      if (*ptr)
545
0
        len = 0; /* not ...~<number> */
546
0
      else if (seen_nonzero)
547
0
        early = 1;
548
0
      else if (len == 1)
549
0
        early = 1; /* "name~" is "name~1"! */
550
0
    }
551
0
  }
552
0
  if (len) {
553
0
    struct strbuf truname = STRBUF_INIT;
554
0
    strbuf_addf(&truname, "refs/heads/%s", remote);
555
0
    strbuf_setlen(&truname, truname.len - len);
556
0
    if (refs_ref_exists(get_main_ref_store(the_repository), truname.buf)) {
557
0
      strbuf_addf(msg,
558
0
            "%s\t\tbranch '%s'%s of .\n",
559
0
            oid_to_hex(&remote_head->object.oid),
560
0
            truname.buf + 11,
561
0
            (early ? " (early part)" : ""));
562
0
      strbuf_release(&truname);
563
0
      goto cleanup;
564
0
    }
565
0
    strbuf_release(&truname);
566
0
  }
567
568
0
  desc = merge_remote_util(remote_head);
569
0
  if (desc && desc->obj && desc->obj->type == OBJ_TAG) {
570
0
    strbuf_addf(msg, "%s\t\t%s '%s'\n",
571
0
          oid_to_hex(&desc->obj->oid),
572
0
          type_name(desc->obj->type),
573
0
          remote);
574
0
    goto cleanup;
575
0
  }
576
577
0
  strbuf_addf(msg, "%s\t\tcommit '%s'\n",
578
0
    oid_to_hex(&remote_head->object.oid), remote);
579
0
cleanup:
580
0
  free(found_ref);
581
0
  strbuf_release(&bname);
582
0
}
583
584
static void parse_branch_merge_options(char *bmo)
585
0
{
586
0
  const char **argv;
587
0
  int argc;
588
589
0
  if (!bmo)
590
0
    return;
591
0
  argc = split_cmdline(bmo, &argv);
592
0
  if (argc < 0)
593
0
    die(_("Bad branch.%s.mergeoptions string: %s"), branch,
594
0
        _(split_cmdline_strerror(argc)));
595
0
  REALLOC_ARRAY(argv, argc + 2);
596
0
  MOVE_ARRAY(argv + 1, argv, argc + 1);
597
0
  argc++;
598
0
  argv[0] = "branch.*.mergeoptions";
599
0
  parse_options(argc, argv, NULL, builtin_merge_options,
600
0
          builtin_merge_usage, 0);
601
0
  free(argv);
602
0
}
603
604
static int git_merge_config(const char *k, const char *v,
605
          const struct config_context *ctx, void *cb)
606
0
{
607
0
  int status;
608
0
  const char *str;
609
610
0
  if (branch &&
611
0
      skip_prefix(k, "branch.", &str) &&
612
0
      skip_prefix(str, branch, &str) &&
613
0
      !strcmp(str, ".mergeoptions")) {
614
0
    free(branch_mergeoptions);
615
0
    branch_mergeoptions = xstrdup(v);
616
0
    return 0;
617
0
  }
618
619
0
  if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat")) {
620
0
    show_diffstat = git_config_bool(k, v);
621
0
  } else if (!strcmp(k, "merge.verifysignatures")) {
622
0
    verify_signatures = git_config_bool(k, v);
623
0
  } else if (!strcmp(k, "pull.twohead")) {
624
0
    FREE_AND_NULL(pull_twohead);
625
0
    return git_config_string(&pull_twohead, k, v);
626
0
  } else if (!strcmp(k, "pull.octopus")) {
627
0
    FREE_AND_NULL(pull_octopus);
628
0
    return git_config_string(&pull_octopus, k, v);
629
0
  } else if (!strcmp(k, "commit.cleanup")) {
630
0
    return git_config_string(&cleanup_arg, k, v);
631
0
  } else if (!strcmp(k, "merge.ff")) {
632
0
    int boolval = git_parse_maybe_bool(v);
633
0
    if (0 <= boolval) {
634
0
      fast_forward = boolval ? FF_ALLOW : FF_NO;
635
0
    } else if (v && !strcmp(v, "only")) {
636
0
      fast_forward = FF_ONLY;
637
0
    } /* do not barf on values from future versions of git */
638
0
    return 0;
639
0
  } else if (!strcmp(k, "merge.defaulttoupstream")) {
640
0
    default_to_upstream = git_config_bool(k, v);
641
0
    return 0;
642
0
  } else if (!strcmp(k, "commit.gpgsign")) {
643
0
    sign_commit = git_config_bool(k, v) ? "" : NULL;
644
0
    return 0;
645
0
  } else if (!strcmp(k, "gpg.mintrustlevel")) {
646
0
    check_trust_level = 0;
647
0
  } else if (!strcmp(k, "merge.autostash")) {
648
0
    autostash = git_config_bool(k, v);
649
0
    return 0;
650
0
  }
651
652
0
  status = fmt_merge_msg_config(k, v, ctx, cb);
653
0
  if (status)
654
0
    return status;
655
0
  return git_diff_ui_config(k, v, ctx, cb);
656
0
}
657
658
static int read_tree_trivial(struct object_id *common, struct object_id *head,
659
           struct object_id *one)
660
0
{
661
0
  int i, nr_trees = 0;
662
0
  struct tree *trees[MAX_UNPACK_TREES];
663
0
  struct tree_desc t[MAX_UNPACK_TREES];
664
0
  struct unpack_trees_options opts;
665
666
0
  memset(&opts, 0, sizeof(opts));
667
0
  opts.head_idx = 2;
668
0
  opts.src_index = the_repository->index;
669
0
  opts.dst_index = the_repository->index;
670
0
  opts.update = 1;
671
0
  opts.verbose_update = 1;
672
0
  opts.trivial_merges_only = 1;
673
0
  opts.merge = 1;
674
0
  opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
675
0
  trees[nr_trees] = parse_tree_indirect(common);
676
0
  if (!trees[nr_trees++])
677
0
    return -1;
678
0
  trees[nr_trees] = parse_tree_indirect(head);
679
0
  if (!trees[nr_trees++])
680
0
    return -1;
681
0
  trees[nr_trees] = parse_tree_indirect(one);
682
0
  if (!trees[nr_trees++])
683
0
    return -1;
684
0
  opts.fn = threeway_merge;
685
0
  cache_tree_free(&the_repository->index->cache_tree);
686
0
  for (i = 0; i < nr_trees; i++) {
687
0
    parse_tree(trees[i]);
688
0
    init_tree_desc(t+i, &trees[i]->object.oid,
689
0
             trees[i]->buffer, trees[i]->size);
690
0
  }
691
0
  if (unpack_trees(nr_trees, t, &opts))
692
0
    return -1;
693
0
  return 0;
694
0
}
695
696
static void write_tree_trivial(struct object_id *oid)
697
0
{
698
0
  if (write_index_as_tree(oid, the_repository->index, get_index_file(), 0, NULL))
699
0
    die(_("git write-tree failed to write a tree"));
700
0
}
701
702
static int try_merge_strategy(const char *strategy, struct commit_list *common,
703
            struct commit_list *remoteheads,
704
            struct commit *head)
705
0
{
706
0
  const char *head_arg = "HEAD";
707
708
0
  if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET,
709
0
           SKIP_IF_UNCHANGED, 0, NULL, NULL,
710
0
           NULL) < 0)
711
0
    die(_("Unable to write index."));
712
713
0
  if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree") ||
714
0
      !strcmp(strategy, "ort")) {
715
0
    struct lock_file lock = LOCK_INIT;
716
0
    int clean, x;
717
0
    struct commit *result;
718
0
    struct commit_list *reversed = NULL;
719
0
    struct merge_options o;
720
0
    struct commit_list *j;
721
722
0
    if (remoteheads->next) {
723
0
      error(_("Not handling anything other than two heads merge."));
724
0
      return 2;
725
0
    }
726
727
0
    init_ui_merge_options(&o, the_repository);
728
0
    if (!strcmp(strategy, "subtree"))
729
0
      o.subtree_shift = "";
730
731
0
    o.show_rename_progress =
732
0
      show_progress == -1 ? isatty(2) : show_progress;
733
734
0
    for (x = 0; x < xopts.nr; x++)
735
0
      if (parse_merge_opt(&o, xopts.v[x]))
736
0
        die(_("unknown strategy option: -X%s"), xopts.v[x]);
737
738
0
    o.branch1 = head_arg;
739
0
    o.branch2 = merge_remote_util(remoteheads->item)->name;
740
741
0
    for (j = common; j; j = j->next)
742
0
      commit_list_insert(j->item, &reversed);
743
744
0
    repo_hold_locked_index(the_repository, &lock,
745
0
               LOCK_DIE_ON_ERROR);
746
0
    if (!strcmp(strategy, "ort"))
747
0
      clean = merge_ort_recursive(&o, head, remoteheads->item,
748
0
                reversed, &result);
749
0
    else
750
0
      clean = merge_recursive(&o, head, remoteheads->item,
751
0
            reversed, &result);
752
0
    free_commit_list(reversed);
753
754
0
    if (clean < 0) {
755
0
      rollback_lock_file(&lock);
756
0
      return 2;
757
0
    }
758
0
    if (write_locked_index(the_repository->index, &lock,
759
0
               COMMIT_LOCK | SKIP_IF_UNCHANGED))
760
0
      die(_("unable to write %s"), get_index_file());
761
0
    return clean ? 0 : 1;
762
0
  } else {
763
0
    return try_merge_command(the_repository,
764
0
           strategy, xopts.nr, xopts.v,
765
0
           common, head_arg, remoteheads);
766
0
  }
767
0
}
768
769
static void count_diff_files(struct diff_queue_struct *q,
770
           struct diff_options *opt UNUSED, void *data)
771
0
{
772
0
  int *count = data;
773
774
0
  (*count) += q->nr;
775
0
}
776
777
static int count_unmerged_entries(void)
778
0
{
779
0
  int i, ret = 0;
780
781
0
  for (i = 0; i < the_repository->index->cache_nr; i++)
782
0
    if (ce_stage(the_repository->index->cache[i]))
783
0
      ret++;
784
785
0
  return ret;
786
0
}
787
788
static void add_strategies(const char *string, unsigned attr)
789
0
{
790
0
  int i;
791
792
0
  if (string) {
793
0
    struct string_list list = STRING_LIST_INIT_DUP;
794
0
    struct string_list_item *item;
795
0
    string_list_split(&list, string, ' ', -1);
796
0
    for_each_string_list_item(item, &list)
797
0
      append_strategy(get_strategy(item->string));
798
0
    string_list_clear(&list, 0);
799
0
    return;
800
0
  }
801
0
  for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
802
0
    if (all_strategy[i].attr & attr)
803
0
      append_strategy(&all_strategy[i]);
804
805
0
}
806
807
static void read_merge_msg(struct strbuf *msg)
808
0
{
809
0
  const char *filename = git_path_merge_msg(the_repository);
810
0
  strbuf_reset(msg);
811
0
  if (strbuf_read_file(msg, filename, 0) < 0)
812
0
    die_errno(_("Could not read from '%s'"), filename);
813
0
}
814
815
static void write_merge_state(struct commit_list *);
816
static void abort_commit(struct commit_list *remoteheads, const char *err_msg)
817
0
{
818
0
  if (err_msg)
819
0
    error("%s", err_msg);
820
0
  fprintf(stderr,
821
0
    _("Not committing merge; use 'git commit' to complete the merge.\n"));
822
0
  write_merge_state(remoteheads);
823
0
  exit(1);
824
0
}
825
826
static const char merge_editor_comment[] =
827
N_("Please enter a commit message to explain why this merge is necessary,\n"
828
   "especially if it merges an updated upstream into a topic branch.\n"
829
   "\n");
830
831
static const char scissors_editor_comment[] =
832
N_("An empty message aborts the commit.\n");
833
834
static const char no_scissors_editor_comment[] =
835
N_("Lines starting with '%s' will be ignored, and an empty message aborts\n"
836
   "the commit.\n");
837
838
static void write_merge_heads(struct commit_list *);
839
static void prepare_to_commit(struct commit_list *remoteheads)
840
0
{
841
0
  struct strbuf msg = STRBUF_INIT;
842
0
  const char *index_file = get_index_file();
843
844
0
  if (!no_verify) {
845
0
    int invoked_hook;
846
847
0
    if (run_commit_hook(0 < option_edit, index_file, &invoked_hook,
848
0
            "pre-merge-commit", NULL))
849
0
      abort_commit(remoteheads, NULL);
850
    /*
851
     * Re-read the index as pre-merge-commit hook could have updated it,
852
     * and write it out as a tree.  We must do this before we invoke
853
     * the editor and after we invoke run_status above.
854
     */
855
0
    if (invoked_hook)
856
0
      discard_index(the_repository->index);
857
0
  }
858
0
  read_index_from(the_repository->index, index_file, get_git_dir());
859
0
  strbuf_addbuf(&msg, &merge_msg);
860
0
  if (squash)
861
0
    BUG("the control must not reach here under --squash");
862
0
  if (0 < option_edit) {
863
0
    strbuf_addch(&msg, '\n');
864
0
    if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
865
0
      wt_status_append_cut_line(&msg);
866
0
      strbuf_commented_addf(&msg, comment_line_str, "\n");
867
0
    }
868
0
    strbuf_commented_addf(&msg, comment_line_str,
869
0
              _(merge_editor_comment));
870
0
    if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
871
0
      strbuf_commented_addf(&msg, comment_line_str,
872
0
                _(scissors_editor_comment));
873
0
    else
874
0
      strbuf_commented_addf(&msg, comment_line_str,
875
0
        _(no_scissors_editor_comment), comment_line_str);
876
0
  }
877
0
  if (signoff)
878
0
    append_signoff(&msg, ignored_log_message_bytes(msg.buf, msg.len), 0);
879
0
  write_merge_heads(remoteheads);
880
0
  write_file_buf(git_path_merge_msg(the_repository), msg.buf, msg.len);
881
0
  if (run_commit_hook(0 < option_edit, get_index_file(), NULL,
882
0
          "prepare-commit-msg",
883
0
          git_path_merge_msg(the_repository), "merge", NULL))
884
0
    abort_commit(remoteheads, NULL);
885
0
  if (0 < option_edit) {
886
0
    if (launch_editor(git_path_merge_msg(the_repository), NULL, NULL))
887
0
      abort_commit(remoteheads, NULL);
888
0
  }
889
890
0
  if (!no_verify && run_commit_hook(0 < option_edit, get_index_file(),
891
0
            NULL, "commit-msg",
892
0
            git_path_merge_msg(the_repository), NULL))
893
0
    abort_commit(remoteheads, NULL);
894
895
0
  read_merge_msg(&msg);
896
0
  cleanup_message(&msg, cleanup_mode, 0);
897
0
  if (!msg.len)
898
0
    abort_commit(remoteheads, _("Empty commit message."));
899
0
  strbuf_release(&merge_msg);
900
0
  strbuf_addbuf(&merge_msg, &msg);
901
0
  strbuf_release(&msg);
902
0
}
903
904
static int merge_trivial(struct commit *head, struct commit_list *remoteheads)
905
0
{
906
0
  struct object_id result_tree, result_commit;
907
0
  struct commit_list *parents = NULL, **pptr = &parents;
908
909
0
  if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET,
910
0
           SKIP_IF_UNCHANGED, 0, NULL, NULL,
911
0
           NULL) < 0)
912
0
    return error(_("Unable to write index."));
913
914
0
  write_tree_trivial(&result_tree);
915
0
  printf(_("Wonderful.\n"));
916
0
  pptr = commit_list_append(head, pptr);
917
0
  pptr = commit_list_append(remoteheads->item, pptr);
918
0
  prepare_to_commit(remoteheads);
919
0
  if (commit_tree(merge_msg.buf, merge_msg.len, &result_tree, parents,
920
0
      &result_commit, NULL, sign_commit))
921
0
    die(_("failed to write commit object"));
922
0
  finish(head, remoteheads, &result_commit, "In-index merge");
923
924
0
  remove_merge_branch_state(the_repository);
925
0
  free_commit_list(parents);
926
0
  return 0;
927
0
}
928
929
static int finish_automerge(struct commit *head,
930
          int head_subsumed,
931
          struct commit_list *common,
932
          struct commit_list *remoteheads,
933
          struct object_id *result_tree,
934
          const char *wt_strategy)
935
0
{
936
0
  struct commit_list *parents = NULL;
937
0
  struct strbuf buf = STRBUF_INIT;
938
0
  struct object_id result_commit;
939
940
0
  write_tree_trivial(result_tree);
941
0
  free_commit_list(common);
942
0
  parents = remoteheads;
943
0
  if (!head_subsumed || fast_forward == FF_NO)
944
0
    commit_list_insert(head, &parents);
945
0
  prepare_to_commit(remoteheads);
946
0
  if (commit_tree(merge_msg.buf, merge_msg.len, result_tree, parents,
947
0
      &result_commit, NULL, sign_commit))
948
0
    die(_("failed to write commit object"));
949
0
  strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
950
0
  finish(head, remoteheads, &result_commit, buf.buf);
951
952
0
  strbuf_release(&buf);
953
0
  remove_merge_branch_state(the_repository);
954
0
  free_commit_list(parents);
955
0
  return 0;
956
0
}
957
958
static int suggest_conflicts(void)
959
0
{
960
0
  const char *filename;
961
0
  FILE *fp;
962
0
  struct strbuf msgbuf = STRBUF_INIT;
963
964
0
  filename = git_path_merge_msg(the_repository);
965
0
  fp = xfopen(filename, "a");
966
967
  /*
968
   * We can't use cleanup_mode because if we're not using the editor,
969
   * get_cleanup_mode will return COMMIT_MSG_CLEANUP_SPACE instead, even
970
   * though the message is meant to be processed later by git-commit.
971
   * Thus, we will get the cleanup mode which is returned when we _are_
972
   * using an editor.
973
   */
974
0
  append_conflicts_hint(the_repository->index, &msgbuf,
975
0
            get_cleanup_mode(cleanup_arg, 1));
976
0
  fputs(msgbuf.buf, fp);
977
0
  strbuf_release(&msgbuf);
978
0
  fclose(fp);
979
0
  repo_rerere(the_repository, allow_rerere_auto);
980
0
  printf(_("Automatic merge failed; "
981
0
      "fix conflicts and then commit the result.\n"));
982
0
  return 1;
983
0
}
984
985
static int evaluate_result(void)
986
0
{
987
0
  int cnt = 0;
988
0
  struct rev_info rev;
989
990
  /* Check how many files differ. */
991
0
  repo_init_revisions(the_repository, &rev, "");
992
0
  setup_revisions(0, NULL, &rev, NULL);
993
0
  rev.diffopt.output_format |=
994
0
    DIFF_FORMAT_CALLBACK;
995
0
  rev.diffopt.format_callback = count_diff_files;
996
0
  rev.diffopt.format_callback_data = &cnt;
997
0
  run_diff_files(&rev, 0);
998
999
  /*
1000
   * Check how many unmerged entries are
1001
   * there.
1002
   */
1003
0
  cnt += count_unmerged_entries();
1004
1005
0
  release_revisions(&rev);
1006
0
  return cnt;
1007
0
}
1008
1009
/*
1010
 * Pretend as if the user told us to merge with the remote-tracking
1011
 * branch we have for the upstream of the current branch
1012
 */
1013
static int setup_with_upstream(const char ***argv)
1014
0
{
1015
0
  struct branch *branch = branch_get(NULL);
1016
0
  int i;
1017
0
  const char **args;
1018
1019
0
  if (!branch)
1020
0
    die(_("No current branch."));
1021
0
  if (!branch->remote_name)
1022
0
    die(_("No remote for the current branch."));
1023
0
  if (!branch->merge_nr)
1024
0
    die(_("No default upstream defined for the current branch."));
1025
1026
0
  args = xcalloc(st_add(branch->merge_nr, 1), sizeof(char *));
1027
0
  for (i = 0; i < branch->merge_nr; i++) {
1028
0
    if (!branch->merge[i]->dst)
1029
0
      die(_("No remote-tracking branch for %s from %s"),
1030
0
          branch->merge[i]->src, branch->remote_name);
1031
0
    args[i] = branch->merge[i]->dst;
1032
0
  }
1033
0
  args[i] = NULL;
1034
0
  *argv = args;
1035
0
  return i;
1036
0
}
1037
1038
static void write_merge_heads(struct commit_list *remoteheads)
1039
0
{
1040
0
  struct commit_list *j;
1041
0
  struct strbuf buf = STRBUF_INIT;
1042
1043
0
  for (j = remoteheads; j; j = j->next) {
1044
0
    struct object_id *oid;
1045
0
    struct commit *c = j->item;
1046
0
    struct merge_remote_desc *desc;
1047
1048
0
    desc = merge_remote_util(c);
1049
0
    if (desc && desc->obj) {
1050
0
      oid = &desc->obj->oid;
1051
0
    } else {
1052
0
      oid = &c->object.oid;
1053
0
    }
1054
0
    strbuf_addf(&buf, "%s\n", oid_to_hex(oid));
1055
0
  }
1056
0
  write_file_buf(git_path_merge_head(the_repository), buf.buf, buf.len);
1057
1058
0
  strbuf_reset(&buf);
1059
0
  if (fast_forward == FF_NO)
1060
0
    strbuf_addstr(&buf, "no-ff");
1061
0
  write_file_buf(git_path_merge_mode(the_repository), buf.buf, buf.len);
1062
0
  strbuf_release(&buf);
1063
0
}
1064
1065
static void write_merge_state(struct commit_list *remoteheads)
1066
0
{
1067
0
  write_merge_heads(remoteheads);
1068
0
  strbuf_addch(&merge_msg, '\n');
1069
0
  write_file_buf(git_path_merge_msg(the_repository), merge_msg.buf,
1070
0
           merge_msg.len);
1071
0
}
1072
1073
static int default_edit_option(void)
1074
0
{
1075
0
  static const char name[] = "GIT_MERGE_AUTOEDIT";
1076
0
  const char *e = getenv(name);
1077
0
  struct stat st_stdin, st_stdout;
1078
1079
0
  if (have_message)
1080
    /* an explicit -m msg without --[no-]edit */
1081
0
    return 0;
1082
1083
0
  if (e) {
1084
0
    int v = git_parse_maybe_bool(e);
1085
0
    if (v < 0)
1086
0
      die(_("Bad value '%s' in environment '%s'"), e, name);
1087
0
    return v;
1088
0
  }
1089
1090
  /* Use editor if stdin and stdout are the same and is a tty */
1091
0
  return (!fstat(0, &st_stdin) &&
1092
0
    !fstat(1, &st_stdout) &&
1093
0
    isatty(0) && isatty(1) &&
1094
0
    st_stdin.st_dev == st_stdout.st_dev &&
1095
0
    st_stdin.st_ino == st_stdout.st_ino &&
1096
0
    st_stdin.st_mode == st_stdout.st_mode);
1097
0
}
1098
1099
static struct commit_list *reduce_parents(struct commit *head_commit,
1100
            int *head_subsumed,
1101
            struct commit_list *remoteheads)
1102
0
{
1103
0
  struct commit_list *parents, **remotes;
1104
1105
  /*
1106
   * Is the current HEAD reachable from another commit being
1107
   * merged?  If so we do not want to record it as a parent of
1108
   * the resulting merge, unless --no-ff is given.  We will flip
1109
   * this variable to 0 when we find HEAD among the independent
1110
   * tips being merged.
1111
   */
1112
0
  *head_subsumed = 1;
1113
1114
  /* Find what parents to record by checking independent ones. */
1115
0
  parents = reduce_heads(remoteheads);
1116
0
  free_commit_list(remoteheads);
1117
1118
0
  remoteheads = NULL;
1119
0
  remotes = &remoteheads;
1120
0
  while (parents) {
1121
0
    struct commit *commit = pop_commit(&parents);
1122
0
    if (commit == head_commit)
1123
0
      *head_subsumed = 0;
1124
0
    else
1125
0
      remotes = &commit_list_insert(commit, remotes)->next;
1126
0
  }
1127
0
  return remoteheads;
1128
0
}
1129
1130
static void prepare_merge_message(struct strbuf *merge_names, struct strbuf *merge_msg)
1131
0
{
1132
0
  struct fmt_merge_msg_opts opts;
1133
1134
0
  memset(&opts, 0, sizeof(opts));
1135
0
  opts.add_title = !have_message;
1136
0
  opts.shortlog_len = shortlog_len;
1137
0
  opts.credit_people = (0 < option_edit);
1138
0
  opts.into_name = into_name;
1139
1140
0
  fmt_merge_msg(merge_names, merge_msg, &opts);
1141
0
  if (merge_msg->len)
1142
0
    strbuf_setlen(merge_msg, merge_msg->len - 1);
1143
0
}
1144
1145
static void handle_fetch_head(struct commit_list **remotes, struct strbuf *merge_names)
1146
0
{
1147
0
  const char *filename;
1148
0
  int fd, pos, npos;
1149
0
  struct strbuf fetch_head_file = STRBUF_INIT;
1150
0
  const unsigned hexsz = the_hash_algo->hexsz;
1151
1152
0
  if (!merge_names)
1153
0
    merge_names = &fetch_head_file;
1154
1155
0
  filename = git_path_fetch_head(the_repository);
1156
0
  fd = xopen(filename, O_RDONLY);
1157
1158
0
  if (strbuf_read(merge_names, fd, 0) < 0)
1159
0
    die_errno(_("could not read '%s'"), filename);
1160
0
  if (close(fd) < 0)
1161
0
    die_errno(_("could not close '%s'"), filename);
1162
1163
0
  for (pos = 0; pos < merge_names->len; pos = npos) {
1164
0
    struct object_id oid;
1165
0
    char *ptr;
1166
0
    struct commit *commit;
1167
1168
0
    ptr = strchr(merge_names->buf + pos, '\n');
1169
0
    if (ptr)
1170
0
      npos = ptr - merge_names->buf + 1;
1171
0
    else
1172
0
      npos = merge_names->len;
1173
1174
0
    if (npos - pos < hexsz + 2 ||
1175
0
        get_oid_hex(merge_names->buf + pos, &oid))
1176
0
      commit = NULL; /* bad */
1177
0
    else if (memcmp(merge_names->buf + pos + hexsz, "\t\t", 2))
1178
0
      continue; /* not-for-merge */
1179
0
    else {
1180
0
      char saved = merge_names->buf[pos + hexsz];
1181
0
      merge_names->buf[pos + hexsz] = '\0';
1182
0
      commit = get_merge_parent(merge_names->buf + pos);
1183
0
      merge_names->buf[pos + hexsz] = saved;
1184
0
    }
1185
0
    if (!commit) {
1186
0
      if (ptr)
1187
0
        *ptr = '\0';
1188
0
      die(_("not something we can merge in %s: %s"),
1189
0
          filename, merge_names->buf + pos);
1190
0
    }
1191
0
    remotes = &commit_list_insert(commit, remotes)->next;
1192
0
  }
1193
1194
0
  if (merge_names == &fetch_head_file)
1195
0
    strbuf_release(&fetch_head_file);
1196
0
}
1197
1198
static struct commit_list *collect_parents(struct commit *head_commit,
1199
             int *head_subsumed,
1200
             int argc, const char **argv,
1201
             struct strbuf *merge_msg)
1202
0
{
1203
0
  int i;
1204
0
  struct commit_list *remoteheads = NULL;
1205
0
  struct commit_list **remotes = &remoteheads;
1206
0
  struct strbuf merge_names = STRBUF_INIT, *autogen = NULL;
1207
1208
0
  if (merge_msg && (!have_message || shortlog_len))
1209
0
    autogen = &merge_names;
1210
1211
0
  if (head_commit)
1212
0
    remotes = &commit_list_insert(head_commit, remotes)->next;
1213
1214
0
  if (argc == 1 && !strcmp(argv[0], "FETCH_HEAD")) {
1215
0
    handle_fetch_head(remotes, autogen);
1216
0
    remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1217
0
  } else {
1218
0
    for (i = 0; i < argc; i++) {
1219
0
      struct commit *commit = get_merge_parent(argv[i]);
1220
0
      if (!commit)
1221
0
        help_unknown_ref(argv[i], "merge",
1222
0
             _("not something we can merge"));
1223
0
      remotes = &commit_list_insert(commit, remotes)->next;
1224
0
    }
1225
0
    remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1226
0
    if (autogen) {
1227
0
      struct commit_list *p;
1228
0
      for (p = remoteheads; p; p = p->next)
1229
0
        merge_name(merge_remote_util(p->item)->name, autogen);
1230
0
    }
1231
0
  }
1232
1233
0
  if (autogen) {
1234
0
    prepare_merge_message(autogen, merge_msg);
1235
0
    strbuf_release(autogen);
1236
0
  }
1237
1238
0
  return remoteheads;
1239
0
}
1240
1241
static int merging_a_throwaway_tag(struct commit *commit)
1242
0
{
1243
0
  char *tag_ref;
1244
0
  struct object_id oid;
1245
0
  int is_throwaway_tag = 0;
1246
1247
  /* Are we merging a tag? */
1248
0
  if (!merge_remote_util(commit) ||
1249
0
      !merge_remote_util(commit)->obj ||
1250
0
      merge_remote_util(commit)->obj->type != OBJ_TAG)
1251
0
    return is_throwaway_tag;
1252
1253
  /*
1254
   * Now we know we are merging a tag object.  Are we downstream
1255
   * and following the tags from upstream?  If so, we must have
1256
   * the tag object pointed at by "refs/tags/$T" where $T is the
1257
   * tagname recorded in the tag object.  We want to allow such
1258
   * a "just to catch up" merge to fast-forward.
1259
   *
1260
   * Otherwise, we are playing an integrator's role, making a
1261
   * merge with a throw-away tag from a contributor with
1262
   * something like "git pull $contributor $signed_tag".
1263
   * We want to forbid such a merge from fast-forwarding
1264
   * by default; otherwise we would not keep the signature
1265
   * anywhere.
1266
   */
1267
0
  tag_ref = xstrfmt("refs/tags/%s",
1268
0
        ((struct tag *)merge_remote_util(commit)->obj)->tag);
1269
0
  if (!refs_read_ref(get_main_ref_store(the_repository), tag_ref, &oid) &&
1270
0
      oideq(&oid, &merge_remote_util(commit)->obj->oid))
1271
0
    is_throwaway_tag = 0;
1272
0
  else
1273
0
    is_throwaway_tag = 1;
1274
0
  free(tag_ref);
1275
0
  return is_throwaway_tag;
1276
0
}
1277
1278
int cmd_merge(int argc, const char **argv, const char *prefix)
1279
0
{
1280
0
  struct object_id result_tree, stash, head_oid;
1281
0
  struct commit *head_commit;
1282
0
  struct strbuf buf = STRBUF_INIT;
1283
0
  int i, ret = 0, head_subsumed;
1284
0
  int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1285
0
  struct commit_list *common = NULL;
1286
0
  const char *best_strategy = NULL, *wt_strategy = NULL;
1287
0
  struct commit_list *remoteheads = NULL, *p;
1288
0
  void *branch_to_free;
1289
0
  int orig_argc = argc;
1290
1291
0
  if (argc == 2 && !strcmp(argv[1], "-h"))
1292
0
    usage_with_options(builtin_merge_usage, builtin_merge_options);
1293
1294
0
  prepare_repo_settings(the_repository);
1295
0
  the_repository->settings.command_requires_full_index = 0;
1296
1297
  /*
1298
   * Check if we are _not_ on a detached HEAD, i.e. if there is a
1299
   * current branch.
1300
   */
1301
0
  branch = branch_to_free = refs_resolve_refdup(get_main_ref_store(the_repository),
1302
0
                  "HEAD", 0, &head_oid,
1303
0
                  NULL);
1304
0
  if (branch)
1305
0
    skip_prefix(branch, "refs/heads/", &branch);
1306
1307
0
  if (!pull_twohead) {
1308
0
    char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
1309
0
    if (default_strategy && !strcmp(default_strategy, "ort"))
1310
0
      pull_twohead = xstrdup("ort");
1311
0
  }
1312
1313
0
  init_diff_ui_defaults();
1314
0
  git_config(git_merge_config, NULL);
1315
1316
0
  if (!branch || is_null_oid(&head_oid))
1317
0
    head_commit = NULL;
1318
0
  else
1319
0
    head_commit = lookup_commit_or_die(&head_oid, "HEAD");
1320
1321
0
  if (branch_mergeoptions)
1322
0
    parse_branch_merge_options(branch_mergeoptions);
1323
0
  argc = parse_options(argc, argv, prefix, builtin_merge_options,
1324
0
      builtin_merge_usage, 0);
1325
0
  if (shortlog_len < 0)
1326
0
    shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;
1327
1328
0
  if (verbosity < 0 && show_progress == -1)
1329
0
    show_progress = 0;
1330
1331
0
  if (abort_current_merge) {
1332
0
    int nargc = 2;
1333
0
    const char *nargv[] = {"reset", "--merge", NULL};
1334
0
    char stash_oid_hex[GIT_MAX_HEXSZ + 1];
1335
0
    struct object_id stash_oid = {0};
1336
1337
0
    if (orig_argc != 2)
1338
0
      usage_msg_opt(_("--abort expects no arguments"),
1339
0
            builtin_merge_usage, builtin_merge_options);
1340
1341
0
    if (!file_exists(git_path_merge_head(the_repository)))
1342
0
      die(_("There is no merge to abort (MERGE_HEAD missing)."));
1343
1344
0
    if (!refs_read_ref(get_main_ref_store(the_repository), "MERGE_AUTOSTASH", &stash_oid))
1345
0
      refs_delete_ref(get_main_ref_store(the_repository),
1346
0
          "", "MERGE_AUTOSTASH", &stash_oid,
1347
0
          REF_NO_DEREF);
1348
1349
    /* Invoke 'git reset --merge' */
1350
0
    ret = cmd_reset(nargc, nargv, prefix);
1351
1352
0
    if (!is_null_oid(&stash_oid)) {
1353
0
      oid_to_hex_r(stash_oid_hex, &stash_oid);
1354
0
      apply_autostash_oid(stash_oid_hex);
1355
0
    }
1356
1357
0
    goto done;
1358
0
  }
1359
1360
0
  if (quit_current_merge) {
1361
0
    if (orig_argc != 2)
1362
0
      usage_msg_opt(_("--quit expects no arguments"),
1363
0
              builtin_merge_usage,
1364
0
              builtin_merge_options);
1365
1366
0
    remove_merge_branch_state(the_repository);
1367
0
    goto done;
1368
0
  }
1369
1370
0
  if (continue_current_merge) {
1371
0
    int nargc = 1;
1372
0
    const char *nargv[] = {"commit", NULL};
1373
1374
0
    if (orig_argc != 2)
1375
0
      usage_msg_opt(_("--continue expects no arguments"),
1376
0
            builtin_merge_usage, builtin_merge_options);
1377
1378
0
    if (!file_exists(git_path_merge_head(the_repository)))
1379
0
      die(_("There is no merge in progress (MERGE_HEAD missing)."));
1380
1381
    /* Invoke 'git commit' */
1382
0
    ret = cmd_commit(nargc, nargv, prefix);
1383
0
    goto done;
1384
0
  }
1385
1386
0
  if (repo_read_index_unmerged(the_repository))
1387
0
    die_resolve_conflict("merge");
1388
1389
0
  if (file_exists(git_path_merge_head(the_repository))) {
1390
    /*
1391
     * There is no unmerged entry, don't advise 'git
1392
     * add/rm <file>', just 'git commit'.
1393
     */
1394
0
    if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
1395
0
      die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1396
0
          "Please, commit your changes before you merge."));
1397
0
    else
1398
0
      die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1399
0
  }
1400
0
  if (refs_ref_exists(get_main_ref_store(the_repository), "CHERRY_PICK_HEAD")) {
1401
0
    if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
1402
0
      die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1403
0
          "Please, commit your changes before you merge."));
1404
0
    else
1405
0
      die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1406
0
  }
1407
0
  resolve_undo_clear_index(the_repository->index);
1408
1409
0
  if (option_edit < 0)
1410
0
    option_edit = default_edit_option();
1411
1412
0
  cleanup_mode = get_cleanup_mode(cleanup_arg, 0 < option_edit);
1413
1414
0
  if (verbosity < 0)
1415
0
    show_diffstat = 0;
1416
1417
0
  if (squash) {
1418
0
    if (fast_forward == FF_NO)
1419
0
      die(_("options '%s' and '%s' cannot be used together"), "--squash", "--no-ff.");
1420
0
    if (option_commit > 0)
1421
0
      die(_("options '%s' and '%s' cannot be used together"), "--squash", "--commit.");
1422
    /*
1423
     * squash can now silently disable option_commit - this is not
1424
     * a problem as it is only overriding the default, not a user
1425
     * supplied option.
1426
     */
1427
0
    option_commit = 0;
1428
0
  }
1429
1430
0
  if (option_commit < 0)
1431
0
    option_commit = 1;
1432
1433
0
  if (!argc) {
1434
0
    if (default_to_upstream)
1435
0
      argc = setup_with_upstream(&argv);
1436
0
    else
1437
0
      die(_("No commit specified and merge.defaultToUpstream not set."));
1438
0
  } else if (argc == 1 && !strcmp(argv[0], "-")) {
1439
0
    argv[0] = "@{-1}";
1440
0
  }
1441
1442
0
  if (!argc)
1443
0
    usage_with_options(builtin_merge_usage,
1444
0
      builtin_merge_options);
1445
1446
0
  if (!head_commit) {
1447
    /*
1448
     * If the merged head is a valid one there is no reason
1449
     * to forbid "git merge" into a branch yet to be born.
1450
     * We do the same for "git pull".
1451
     */
1452
0
    struct object_id *remote_head_oid;
1453
0
    if (squash)
1454
0
      die(_("Squash commit into empty head not supported yet"));
1455
0
    if (fast_forward == FF_NO)
1456
0
      die(_("Non-fast-forward commit does not make sense into "
1457
0
          "an empty head"));
1458
0
    remoteheads = collect_parents(head_commit, &head_subsumed,
1459
0
                argc, argv, NULL);
1460
0
    if (!remoteheads)
1461
0
      die(_("%s - not something we can merge"), argv[0]);
1462
0
    if (remoteheads->next)
1463
0
      die(_("Can merge only exactly one commit into empty head"));
1464
1465
0
    if (verify_signatures)
1466
0
      verify_merge_signature(remoteheads->item, verbosity,
1467
0
                 check_trust_level);
1468
1469
0
    remote_head_oid = &remoteheads->item->object.oid;
1470
0
    read_empty(remote_head_oid);
1471
0
    refs_update_ref(get_main_ref_store(the_repository),
1472
0
        "initial pull", "HEAD", remote_head_oid, NULL,
1473
0
        0,
1474
0
        UPDATE_REFS_DIE_ON_ERR);
1475
0
    goto done;
1476
0
  }
1477
1478
  /*
1479
   * All the rest are the commits being merged; prepare
1480
   * the standard merge summary message to be appended
1481
   * to the given message.
1482
   */
1483
0
  remoteheads = collect_parents(head_commit, &head_subsumed,
1484
0
              argc, argv, &merge_msg);
1485
1486
0
  if (!head_commit || !argc)
1487
0
    usage_with_options(builtin_merge_usage,
1488
0
      builtin_merge_options);
1489
1490
0
  if (verify_signatures) {
1491
0
    for (p = remoteheads; p; p = p->next) {
1492
0
      verify_merge_signature(p->item, verbosity,
1493
0
                 check_trust_level);
1494
0
    }
1495
0
  }
1496
1497
0
  strbuf_addstr(&buf, "merge");
1498
0
  for (p = remoteheads; p; p = p->next)
1499
0
    strbuf_addf(&buf, " %s", merge_remote_util(p->item)->name);
1500
0
  setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1501
0
  strbuf_reset(&buf);
1502
1503
0
  for (p = remoteheads; p; p = p->next) {
1504
0
    struct commit *commit = p->item;
1505
0
    strbuf_addf(&buf, "GITHEAD_%s",
1506
0
          oid_to_hex(&commit->object.oid));
1507
0
    setenv(buf.buf, merge_remote_util(commit)->name, 1);
1508
0
    strbuf_reset(&buf);
1509
0
    if (fast_forward != FF_ONLY && merging_a_throwaway_tag(commit))
1510
0
      fast_forward = FF_NO;
1511
0
  }
1512
1513
0
  if (!use_strategies && !pull_twohead &&
1514
0
      remoteheads && !remoteheads->next) {
1515
0
    char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
1516
0
    if (default_strategy)
1517
0
      append_strategy(get_strategy(default_strategy));
1518
0
  }
1519
0
  if (!use_strategies) {
1520
0
    if (!remoteheads)
1521
0
      ; /* already up-to-date */
1522
0
    else if (!remoteheads->next)
1523
0
      add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1524
0
    else
1525
0
      add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1526
0
  }
1527
1528
0
  for (i = 0; i < use_strategies_nr; i++) {
1529
0
    if (use_strategies[i]->attr & NO_FAST_FORWARD)
1530
0
      fast_forward = FF_NO;
1531
0
    if (use_strategies[i]->attr & NO_TRIVIAL)
1532
0
      allow_trivial = 0;
1533
0
  }
1534
1535
0
  if (!remoteheads)
1536
0
    ; /* already up-to-date */
1537
0
  else if (!remoteheads->next) {
1538
0
    if (repo_get_merge_bases(the_repository, head_commit,
1539
0
           remoteheads->item, &common) < 0) {
1540
0
      ret = 2;
1541
0
      goto done;
1542
0
    }
1543
0
  } else {
1544
0
    struct commit_list *list = remoteheads;
1545
0
    commit_list_insert(head_commit, &list);
1546
0
    if (get_octopus_merge_bases(list, &common) < 0) {
1547
0
      free(list);
1548
0
      ret = 2;
1549
0
      goto done;
1550
0
    }
1551
0
    free(list);
1552
0
  }
1553
1554
0
  refs_update_ref(get_main_ref_store(the_repository),
1555
0
      "updating ORIG_HEAD", "ORIG_HEAD",
1556
0
      &head_commit->object.oid, NULL, 0,
1557
0
      UPDATE_REFS_DIE_ON_ERR);
1558
1559
0
  if (remoteheads && !common) {
1560
    /* No common ancestors found. */
1561
0
    if (!allow_unrelated_histories)
1562
0
      die(_("refusing to merge unrelated histories"));
1563
    /* otherwise, we need a real merge. */
1564
0
  } else if (!remoteheads ||
1565
0
     (!remoteheads->next && !common->next &&
1566
0
      common->item == remoteheads->item)) {
1567
    /*
1568
     * If head can reach all the merge then we are up to date.
1569
     * but first the most common case of merging one remote.
1570
     */
1571
0
    finish_up_to_date();
1572
0
    goto done;
1573
0
  } else if (fast_forward != FF_NO && !remoteheads->next &&
1574
0
      !common->next &&
1575
0
      oideq(&common->item->object.oid, &head_commit->object.oid)) {
1576
    /* Again the most common case of merging one remote. */
1577
0
    const char *msg = have_message ?
1578
0
      "Fast-forward (no commit created; -m option ignored)" :
1579
0
      "Fast-forward";
1580
0
    struct commit *commit;
1581
1582
0
    if (verbosity >= 0) {
1583
0
      printf(_("Updating %s..%s\n"),
1584
0
             repo_find_unique_abbrev(the_repository, &head_commit->object.oid,
1585
0
                   DEFAULT_ABBREV),
1586
0
             repo_find_unique_abbrev(the_repository, &remoteheads->item->object.oid,
1587
0
                   DEFAULT_ABBREV));
1588
0
    }
1589
0
    commit = remoteheads->item;
1590
0
    if (!commit) {
1591
0
      ret = 1;
1592
0
      goto done;
1593
0
    }
1594
1595
0
    if (autostash)
1596
0
      create_autostash_ref(the_repository, "MERGE_AUTOSTASH");
1597
0
    if (checkout_fast_forward(the_repository,
1598
0
            &head_commit->object.oid,
1599
0
            &commit->object.oid,
1600
0
            overwrite_ignore)) {
1601
0
      apply_autostash_ref(the_repository, "MERGE_AUTOSTASH");
1602
0
      ret = 1;
1603
0
      goto done;
1604
0
    }
1605
1606
0
    finish(head_commit, remoteheads, &commit->object.oid, msg);
1607
0
    remove_merge_branch_state(the_repository);
1608
0
    goto done;
1609
0
  } else if (!remoteheads->next && common->next)
1610
0
    ;
1611
    /*
1612
     * We are not doing octopus and not fast-forward.  Need
1613
     * a real merge.
1614
     */
1615
0
  else if (!remoteheads->next && !common->next && option_commit) {
1616
    /*
1617
     * We are not doing octopus, not fast-forward, and have
1618
     * only one common.
1619
     */
1620
0
    refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
1621
0
    if (allow_trivial && fast_forward != FF_ONLY) {
1622
      /*
1623
       * Must first ensure that index matches HEAD before
1624
       * attempting a trivial merge.
1625
       */
1626
0
      struct tree *head_tree = repo_get_commit_tree(the_repository,
1627
0
                      head_commit);
1628
0
      struct strbuf sb = STRBUF_INIT;
1629
1630
0
      if (repo_index_has_changes(the_repository, head_tree,
1631
0
               &sb)) {
1632
0
        error(_("Your local changes to the following files would be overwritten by merge:\n  %s"),
1633
0
              sb.buf);
1634
0
        strbuf_release(&sb);
1635
0
        ret = 2;
1636
0
        goto done;
1637
0
      }
1638
1639
      /* See if it is really trivial. */
1640
0
      git_committer_info(IDENT_STRICT);
1641
0
      printf(_("Trying really trivial in-index merge...\n"));
1642
0
      if (!read_tree_trivial(&common->item->object.oid,
1643
0
                 &head_commit->object.oid,
1644
0
                 &remoteheads->item->object.oid)) {
1645
0
        ret = merge_trivial(head_commit, remoteheads);
1646
0
        goto done;
1647
0
      }
1648
0
      printf(_("Nope.\n"));
1649
0
    }
1650
0
  } else {
1651
    /*
1652
     * An octopus.  If we can reach all the remote we are up
1653
     * to date.
1654
     */
1655
0
    int up_to_date = 1;
1656
0
    struct commit_list *j;
1657
1658
0
    for (j = remoteheads; j; j = j->next) {
1659
0
      struct commit_list *common_one = NULL;
1660
0
      struct commit *common_item;
1661
1662
      /*
1663
       * Here we *have* to calculate the individual
1664
       * merge_bases again, otherwise "git merge HEAD^
1665
       * HEAD^^" would be missed.
1666
       */
1667
0
      if (repo_get_merge_bases(the_repository, head_commit,
1668
0
             j->item, &common_one) < 0)
1669
0
        exit(128);
1670
1671
0
      common_item = common_one->item;
1672
0
      free_commit_list(common_one);
1673
0
      if (!oideq(&common_item->object.oid, &j->item->object.oid)) {
1674
0
        up_to_date = 0;
1675
0
        break;
1676
0
      }
1677
0
    }
1678
0
    if (up_to_date) {
1679
0
      finish_up_to_date();
1680
0
      goto done;
1681
0
    }
1682
0
  }
1683
1684
0
  if (fast_forward == FF_ONLY)
1685
0
    die_ff_impossible();
1686
1687
0
  if (autostash)
1688
0
    create_autostash_ref(the_repository, "MERGE_AUTOSTASH");
1689
1690
  /* We are going to make a new commit. */
1691
0
  git_committer_info(IDENT_STRICT);
1692
1693
  /*
1694
   * At this point, we need a real merge.  No matter what strategy
1695
   * we use, it would operate on the index, possibly affecting the
1696
   * working tree, and when resolved cleanly, have the desired
1697
   * tree in the index -- this means that the index must be in
1698
   * sync with the head commit.  The strategies are responsible
1699
   * to ensure this.
1700
   *
1701
   * Stash away the local changes so that we can try more than one
1702
   * and/or recover from merge strategies bailing while leaving the
1703
   * index and working tree polluted.
1704
   */
1705
0
  if (save_state(&stash))
1706
0
    oidclr(&stash, the_repository->hash_algo);
1707
1708
0
  for (i = 0; i < use_strategies_nr; i++) {
1709
0
    int ret, cnt;
1710
0
    if (i) {
1711
0
      printf(_("Rewinding the tree to pristine...\n"));
1712
0
      restore_state(&head_commit->object.oid, &stash);
1713
0
    }
1714
0
    if (use_strategies_nr != 1)
1715
0
      printf(_("Trying merge strategy %s...\n"),
1716
0
        use_strategies[i]->name);
1717
    /*
1718
     * Remember which strategy left the state in the working
1719
     * tree.
1720
     */
1721
0
    wt_strategy = use_strategies[i]->name;
1722
1723
0
    ret = try_merge_strategy(wt_strategy,
1724
0
           common, remoteheads,
1725
0
           head_commit);
1726
    /*
1727
     * The backend exits with 1 when conflicts are
1728
     * left to be resolved, with 2 when it does not
1729
     * handle the given merge at all.
1730
     */
1731
0
    if (ret < 2) {
1732
0
      if (!ret) {
1733
        /*
1734
         * This strategy worked; no point in trying
1735
         * another.
1736
         */
1737
0
        merge_was_ok = 1;
1738
0
        best_strategy = wt_strategy;
1739
0
        break;
1740
0
      }
1741
0
      cnt = (use_strategies_nr > 1) ? evaluate_result() : 0;
1742
0
      if (best_cnt <= 0 || cnt <= best_cnt) {
1743
0
        best_strategy = wt_strategy;
1744
0
        best_cnt = cnt;
1745
0
      }
1746
0
    }
1747
0
  }
1748
1749
  /*
1750
   * If we have a resulting tree, that means the strategy module
1751
   * auto resolved the merge cleanly.
1752
   */
1753
0
  if (merge_was_ok && option_commit) {
1754
0
    automerge_was_ok = 1;
1755
0
    ret = finish_automerge(head_commit, head_subsumed,
1756
0
               common, remoteheads,
1757
0
               &result_tree, wt_strategy);
1758
0
    goto done;
1759
0
  }
1760
1761
  /*
1762
   * Pick the result from the best strategy and have the user fix
1763
   * it up.
1764
   */
1765
0
  if (!best_strategy) {
1766
0
    restore_state(&head_commit->object.oid, &stash);
1767
0
    if (use_strategies_nr > 1)
1768
0
      fprintf(stderr,
1769
0
        _("No merge strategy handled the merge.\n"));
1770
0
    else
1771
0
      fprintf(stderr, _("Merge with strategy %s failed.\n"),
1772
0
        use_strategies[0]->name);
1773
0
    apply_autostash_ref(the_repository, "MERGE_AUTOSTASH");
1774
0
    ret = 2;
1775
0
    goto done;
1776
0
  } else if (best_strategy == wt_strategy)
1777
0
    ; /* We already have its result in the working tree. */
1778
0
  else {
1779
0
    printf(_("Rewinding the tree to pristine...\n"));
1780
0
    restore_state(&head_commit->object.oid, &stash);
1781
0
    printf(_("Using the %s strategy to prepare resolving by hand.\n"),
1782
0
      best_strategy);
1783
0
    try_merge_strategy(best_strategy, common, remoteheads,
1784
0
           head_commit);
1785
0
  }
1786
1787
0
  if (squash) {
1788
0
    finish(head_commit, remoteheads, NULL, NULL);
1789
1790
0
    git_test_write_commit_graph_or_die();
1791
0
  } else
1792
0
    write_merge_state(remoteheads);
1793
1794
0
  if (merge_was_ok)
1795
0
    fprintf(stderr, _("Automatic merge went well; "
1796
0
      "stopped before committing as requested\n"));
1797
0
  else
1798
0
    ret = suggest_conflicts();
1799
0
  if (autostash)
1800
0
    printf(_("When finished, apply stashed changes with `git stash pop`\n"));
1801
1802
0
done:
1803
0
  if (!automerge_was_ok) {
1804
0
    free_commit_list(common);
1805
0
    free_commit_list(remoteheads);
1806
0
  }
1807
0
  strbuf_release(&buf);
1808
0
  free(branch_to_free);
1809
0
  free(pull_twohead);
1810
0
  free(pull_octopus);
1811
0
  discard_index(the_repository->index);
1812
0
  return ret;
1813
0
}