cherry-pick/revert: add scissors line on merge conflict
[git] / builtin / pull.c
1 /*
2  * Builtin "git pull"
3  *
4  * Based on git-pull.sh by Junio C Hamano
5  *
6  * Fetch one or more remote refs and merge it/them into the current HEAD.
7  */
8 #define USE_THE_INDEX_COMPATIBILITY_MACROS
9 #include "cache.h"
10 #include "config.h"
11 #include "builtin.h"
12 #include "parse-options.h"
13 #include "exec-cmd.h"
14 #include "run-command.h"
15 #include "sha1-array.h"
16 #include "remote.h"
17 #include "dir.h"
18 #include "refs.h"
19 #include "refspec.h"
20 #include "revision.h"
21 #include "submodule.h"
22 #include "submodule-config.h"
23 #include "tempfile.h"
24 #include "lockfile.h"
25 #include "wt-status.h"
26 #include "commit-reach.h"
27 #include "sequencer.h"
28
29 enum rebase_type {
30         REBASE_INVALID = -1,
31         REBASE_FALSE = 0,
32         REBASE_TRUE,
33         REBASE_PRESERVE,
34         REBASE_MERGES,
35         REBASE_INTERACTIVE
36 };
37
38 /**
39  * Parses the value of --rebase. If value is a false value, returns
40  * REBASE_FALSE. If value is a true value, returns REBASE_TRUE. If value is
41  * "merges", returns REBASE_MERGES. If value is "preserve", returns
42  * REBASE_PRESERVE. If value is a invalid value, dies with a fatal error if
43  * fatal is true, otherwise returns REBASE_INVALID.
44  */
45 static enum rebase_type parse_config_rebase(const char *key, const char *value,
46                 int fatal)
47 {
48         int v = git_parse_maybe_bool(value);
49
50         if (!v)
51                 return REBASE_FALSE;
52         else if (v > 0)
53                 return REBASE_TRUE;
54         else if (!strcmp(value, "preserve") || !strcmp(value, "p"))
55                 return REBASE_PRESERVE;
56         else if (!strcmp(value, "merges") || !strcmp(value, "m"))
57                 return REBASE_MERGES;
58         else if (!strcmp(value, "interactive") || !strcmp(value, "i"))
59                 return REBASE_INTERACTIVE;
60         /*
61          * Please update _git_config() in git-completion.bash when you
62          * add new rebase modes.
63          */
64
65         if (fatal)
66                 die(_("Invalid value for %s: %s"), key, value);
67         else
68                 error(_("Invalid value for %s: %s"), key, value);
69
70         return REBASE_INVALID;
71 }
72
73 /**
74  * Callback for --rebase, which parses arg with parse_config_rebase().
75  */
76 static int parse_opt_rebase(const struct option *opt, const char *arg, int unset)
77 {
78         enum rebase_type *value = opt->value;
79
80         if (arg)
81                 *value = parse_config_rebase("--rebase", arg, 0);
82         else
83                 *value = unset ? REBASE_FALSE : REBASE_TRUE;
84         return *value == REBASE_INVALID ? -1 : 0;
85 }
86
87 static const char * const pull_usage[] = {
88         N_("git pull [<options>] [<repository> [<refspec>...]]"),
89         NULL
90 };
91
92 /* Shared options */
93 static int opt_verbosity;
94 static char *opt_progress;
95 static int recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
96
97 /* Options passed to git-merge or git-rebase */
98 static enum rebase_type opt_rebase = -1;
99 static char *opt_diffstat;
100 static char *opt_log;
101 static char *opt_signoff;
102 static char *opt_squash;
103 static char *opt_commit;
104 static char *opt_edit;
105 static char *cleanup_arg;
106 static char *opt_ff;
107 static char *opt_verify_signatures;
108 static int opt_autostash = -1;
109 static int config_autostash;
110 static struct argv_array opt_strategies = ARGV_ARRAY_INIT;
111 static struct argv_array opt_strategy_opts = ARGV_ARRAY_INIT;
112 static char *opt_gpg_sign;
113 static int opt_allow_unrelated_histories;
114
115 /* Options passed to git-fetch */
116 static char *opt_all;
117 static char *opt_append;
118 static char *opt_upload_pack;
119 static int opt_force;
120 static char *opt_tags;
121 static char *opt_prune;
122 static char *max_children;
123 static int opt_dry_run;
124 static char *opt_keep;
125 static char *opt_depth;
126 static char *opt_unshallow;
127 static char *opt_update_shallow;
128 static char *opt_refmap;
129 static char *opt_ipv4;
130 static char *opt_ipv6;
131
132 static struct option pull_options[] = {
133         /* Shared options */
134         OPT__VERBOSITY(&opt_verbosity),
135         OPT_PASSTHRU(0, "progress", &opt_progress, NULL,
136                 N_("force progress reporting"),
137                 PARSE_OPT_NOARG),
138         { OPTION_CALLBACK, 0, "recurse-submodules",
139                    &recurse_submodules, N_("on-demand"),
140                    N_("control for recursive fetching of submodules"),
141                    PARSE_OPT_OPTARG, option_fetch_parse_recurse_submodules },
142
143         /* Options passed to git-merge or git-rebase */
144         OPT_GROUP(N_("Options related to merging")),
145         { OPTION_CALLBACK, 'r', "rebase", &opt_rebase,
146           "(false|true|merges|preserve|interactive)",
147           N_("incorporate changes by rebasing rather than merging"),
148           PARSE_OPT_OPTARG, parse_opt_rebase },
149         OPT_PASSTHRU('n', NULL, &opt_diffstat, NULL,
150                 N_("do not show a diffstat at the end of the merge"),
151                 PARSE_OPT_NOARG | PARSE_OPT_NONEG),
152         OPT_PASSTHRU(0, "stat", &opt_diffstat, NULL,
153                 N_("show a diffstat at the end of the merge"),
154                 PARSE_OPT_NOARG),
155         OPT_PASSTHRU(0, "summary", &opt_diffstat, NULL,
156                 N_("(synonym to --stat)"),
157                 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN),
158         OPT_PASSTHRU(0, "log", &opt_log, N_("n"),
159                 N_("add (at most <n>) entries from shortlog to merge commit message"),
160                 PARSE_OPT_OPTARG),
161         OPT_PASSTHRU(0, "signoff", &opt_signoff, NULL,
162                 N_("add Signed-off-by:"),
163                 PARSE_OPT_OPTARG),
164         OPT_PASSTHRU(0, "squash", &opt_squash, NULL,
165                 N_("create a single commit instead of doing a merge"),
166                 PARSE_OPT_NOARG),
167         OPT_PASSTHRU(0, "commit", &opt_commit, NULL,
168                 N_("perform a commit if the merge succeeds (default)"),
169                 PARSE_OPT_NOARG),
170         OPT_PASSTHRU(0, "edit", &opt_edit, NULL,
171                 N_("edit message before committing"),
172                 PARSE_OPT_NOARG),
173         OPT_CLEANUP(&cleanup_arg),
174         OPT_PASSTHRU(0, "ff", &opt_ff, NULL,
175                 N_("allow fast-forward"),
176                 PARSE_OPT_NOARG),
177         OPT_PASSTHRU(0, "ff-only", &opt_ff, NULL,
178                 N_("abort if fast-forward is not possible"),
179                 PARSE_OPT_NOARG | PARSE_OPT_NONEG),
180         OPT_PASSTHRU(0, "verify-signatures", &opt_verify_signatures, NULL,
181                 N_("verify that the named commit has a valid GPG signature"),
182                 PARSE_OPT_NOARG),
183         OPT_BOOL(0, "autostash", &opt_autostash,
184                 N_("automatically stash/stash pop before and after rebase")),
185         OPT_PASSTHRU_ARGV('s', "strategy", &opt_strategies, N_("strategy"),
186                 N_("merge strategy to use"),
187                 0),
188         OPT_PASSTHRU_ARGV('X', "strategy-option", &opt_strategy_opts,
189                 N_("option=value"),
190                 N_("option for selected merge strategy"),
191                 0),
192         OPT_PASSTHRU('S', "gpg-sign", &opt_gpg_sign, N_("key-id"),
193                 N_("GPG sign commit"),
194                 PARSE_OPT_OPTARG),
195         OPT_SET_INT(0, "allow-unrelated-histories",
196                     &opt_allow_unrelated_histories,
197                     N_("allow merging unrelated histories"), 1),
198
199         /* Options passed to git-fetch */
200         OPT_GROUP(N_("Options related to fetching")),
201         OPT_PASSTHRU(0, "all", &opt_all, NULL,
202                 N_("fetch from all remotes"),
203                 PARSE_OPT_NOARG),
204         OPT_PASSTHRU('a', "append", &opt_append, NULL,
205                 N_("append to .git/FETCH_HEAD instead of overwriting"),
206                 PARSE_OPT_NOARG),
207         OPT_PASSTHRU(0, "upload-pack", &opt_upload_pack, N_("path"),
208                 N_("path to upload pack on remote end"),
209                 0),
210         OPT__FORCE(&opt_force, N_("force overwrite of local branch"), 0),
211         OPT_PASSTHRU('t', "tags", &opt_tags, NULL,
212                 N_("fetch all tags and associated objects"),
213                 PARSE_OPT_NOARG),
214         OPT_PASSTHRU('p', "prune", &opt_prune, NULL,
215                 N_("prune remote-tracking branches no longer on remote"),
216                 PARSE_OPT_NOARG),
217         OPT_PASSTHRU('j', "jobs", &max_children, N_("n"),
218                 N_("number of submodules pulled in parallel"),
219                 PARSE_OPT_OPTARG),
220         OPT_BOOL(0, "dry-run", &opt_dry_run,
221                 N_("dry run")),
222         OPT_PASSTHRU('k', "keep", &opt_keep, NULL,
223                 N_("keep downloaded pack"),
224                 PARSE_OPT_NOARG),
225         OPT_PASSTHRU(0, "depth", &opt_depth, N_("depth"),
226                 N_("deepen history of shallow clone"),
227                 0),
228         OPT_PASSTHRU(0, "unshallow", &opt_unshallow, NULL,
229                 N_("convert to a complete repository"),
230                 PARSE_OPT_NONEG | PARSE_OPT_NOARG),
231         OPT_PASSTHRU(0, "update-shallow", &opt_update_shallow, NULL,
232                 N_("accept refs that update .git/shallow"),
233                 PARSE_OPT_NOARG),
234         OPT_PASSTHRU(0, "refmap", &opt_refmap, N_("refmap"),
235                 N_("specify fetch refmap"),
236                 PARSE_OPT_NONEG),
237         OPT_PASSTHRU('4',  "ipv4", &opt_ipv4, NULL,
238                 N_("use IPv4 addresses only"),
239                 PARSE_OPT_NOARG),
240         OPT_PASSTHRU('6',  "ipv6", &opt_ipv6, NULL,
241                 N_("use IPv6 addresses only"),
242                 PARSE_OPT_NOARG),
243
244         OPT_END()
245 };
246
247 /**
248  * Pushes "-q" or "-v" switches into arr to match the opt_verbosity level.
249  */
250 static void argv_push_verbosity(struct argv_array *arr)
251 {
252         int verbosity;
253
254         for (verbosity = opt_verbosity; verbosity > 0; verbosity--)
255                 argv_array_push(arr, "-v");
256
257         for (verbosity = opt_verbosity; verbosity < 0; verbosity++)
258                 argv_array_push(arr, "-q");
259 }
260
261 /**
262  * Pushes "-f" switches into arr to match the opt_force level.
263  */
264 static void argv_push_force(struct argv_array *arr)
265 {
266         int force = opt_force;
267         while (force-- > 0)
268                 argv_array_push(arr, "-f");
269 }
270
271 /**
272  * Sets the GIT_REFLOG_ACTION environment variable to the concatenation of argv
273  */
274 static void set_reflog_message(int argc, const char **argv)
275 {
276         int i;
277         struct strbuf msg = STRBUF_INIT;
278
279         for (i = 0; i < argc; i++) {
280                 if (i)
281                         strbuf_addch(&msg, ' ');
282                 strbuf_addstr(&msg, argv[i]);
283         }
284
285         setenv("GIT_REFLOG_ACTION", msg.buf, 0);
286
287         strbuf_release(&msg);
288 }
289
290 /**
291  * If pull.ff is unset, returns NULL. If pull.ff is "true", returns "--ff". If
292  * pull.ff is "false", returns "--no-ff". If pull.ff is "only", returns
293  * "--ff-only". Otherwise, if pull.ff is set to an invalid value, die with an
294  * error.
295  */
296 static const char *config_get_ff(void)
297 {
298         const char *value;
299
300         if (git_config_get_value("pull.ff", &value))
301                 return NULL;
302
303         switch (git_parse_maybe_bool(value)) {
304         case 0:
305                 return "--no-ff";
306         case 1:
307                 return "--ff";
308         }
309
310         if (!strcmp(value, "only"))
311                 return "--ff-only";
312
313         die(_("Invalid value for pull.ff: %s"), value);
314 }
315
316 /**
317  * Returns the default configured value for --rebase. It first looks for the
318  * value of "branch.$curr_branch.rebase", where $curr_branch is the current
319  * branch, and if HEAD is detached or the configuration key does not exist,
320  * looks for the value of "pull.rebase". If both configuration keys do not
321  * exist, returns REBASE_FALSE.
322  */
323 static enum rebase_type config_get_rebase(void)
324 {
325         struct branch *curr_branch = branch_get("HEAD");
326         const char *value;
327
328         if (curr_branch) {
329                 char *key = xstrfmt("branch.%s.rebase", curr_branch->name);
330
331                 if (!git_config_get_value(key, &value)) {
332                         enum rebase_type ret = parse_config_rebase(key, value, 1);
333                         free(key);
334                         return ret;
335                 }
336
337                 free(key);
338         }
339
340         if (!git_config_get_value("pull.rebase", &value))
341                 return parse_config_rebase("pull.rebase", value, 1);
342
343         return REBASE_FALSE;
344 }
345
346 /**
347  * Read config variables.
348  */
349 static int git_pull_config(const char *var, const char *value, void *cb)
350 {
351         if (!strcmp(var, "rebase.autostash")) {
352                 config_autostash = git_config_bool(var, value);
353                 return 0;
354         } else if (!strcmp(var, "submodule.recurse")) {
355                 recurse_submodules = git_config_bool(var, value) ?
356                         RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
357                 return 0;
358         }
359         return git_default_config(var, value, cb);
360 }
361
362 /**
363  * Appends merge candidates from FETCH_HEAD that are not marked not-for-merge
364  * into merge_heads.
365  */
366 static void get_merge_heads(struct oid_array *merge_heads)
367 {
368         const char *filename = git_path_fetch_head(the_repository);
369         FILE *fp;
370         struct strbuf sb = STRBUF_INIT;
371         struct object_id oid;
372
373         fp = xfopen(filename, "r");
374         while (strbuf_getline_lf(&sb, fp) != EOF) {
375                 if (get_oid_hex(sb.buf, &oid))
376                         continue;  /* invalid line: does not start with SHA1 */
377                 if (starts_with(sb.buf + GIT_SHA1_HEXSZ, "\tnot-for-merge\t"))
378                         continue;  /* ref is not-for-merge */
379                 oid_array_append(merge_heads, &oid);
380         }
381         fclose(fp);
382         strbuf_release(&sb);
383 }
384
385 /**
386  * Used by die_no_merge_candidates() as a for_each_remote() callback to
387  * retrieve the name of the remote if the repository only has one remote.
388  */
389 static int get_only_remote(struct remote *remote, void *cb_data)
390 {
391         const char **remote_name = cb_data;
392
393         if (*remote_name)
394                 return -1;
395
396         *remote_name = remote->name;
397         return 0;
398 }
399
400 /**
401  * Dies with the appropriate reason for why there are no merge candidates:
402  *
403  * 1. We fetched from a specific remote, and a refspec was given, but it ended
404  *    up not fetching anything. This is usually because the user provided a
405  *    wildcard refspec which had no matches on the remote end.
406  *
407  * 2. We fetched from a non-default remote, but didn't specify a branch to
408  *    merge. We can't use the configured one because it applies to the default
409  *    remote, thus the user must specify the branches to merge.
410  *
411  * 3. We fetched from the branch's or repo's default remote, but:
412  *
413  *    a. We are not on a branch, so there will never be a configured branch to
414  *       merge with.
415  *
416  *    b. We are on a branch, but there is no configured branch to merge with.
417  *
418  * 4. We fetched from the branch's or repo's default remote, but the configured
419  *    branch to merge didn't get fetched. (Either it doesn't exist, or wasn't
420  *    part of the configured fetch refspec.)
421  */
422 static void NORETURN die_no_merge_candidates(const char *repo, const char **refspecs)
423 {
424         struct branch *curr_branch = branch_get("HEAD");
425         const char *remote = curr_branch ? curr_branch->remote_name : NULL;
426
427         if (*refspecs) {
428                 if (opt_rebase)
429                         fprintf_ln(stderr, _("There is no candidate for rebasing against among the refs that you just fetched."));
430                 else
431                         fprintf_ln(stderr, _("There are no candidates for merging among the refs that you just fetched."));
432                 fprintf_ln(stderr, _("Generally this means that you provided a wildcard refspec which had no\n"
433                                         "matches on the remote end."));
434         } else if (repo && curr_branch && (!remote || strcmp(repo, remote))) {
435                 fprintf_ln(stderr, _("You asked to pull from the remote '%s', but did not specify\n"
436                         "a branch. Because this is not the default configured remote\n"
437                         "for your current branch, you must specify a branch on the command line."),
438                         repo);
439         } else if (!curr_branch) {
440                 fprintf_ln(stderr, _("You are not currently on a branch."));
441                 if (opt_rebase)
442                         fprintf_ln(stderr, _("Please specify which branch you want to rebase against."));
443                 else
444                         fprintf_ln(stderr, _("Please specify which branch you want to merge with."));
445                 fprintf_ln(stderr, _("See git-pull(1) for details."));
446                 fprintf(stderr, "\n");
447                 fprintf_ln(stderr, "    git pull %s %s", _("<remote>"), _("<branch>"));
448                 fprintf(stderr, "\n");
449         } else if (!curr_branch->merge_nr) {
450                 const char *remote_name = NULL;
451
452                 if (for_each_remote(get_only_remote, &remote_name) || !remote_name)
453                         remote_name = _("<remote>");
454
455                 fprintf_ln(stderr, _("There is no tracking information for the current branch."));
456                 if (opt_rebase)
457                         fprintf_ln(stderr, _("Please specify which branch you want to rebase against."));
458                 else
459                         fprintf_ln(stderr, _("Please specify which branch you want to merge with."));
460                 fprintf_ln(stderr, _("See git-pull(1) for details."));
461                 fprintf(stderr, "\n");
462                 fprintf_ln(stderr, "    git pull %s %s", _("<remote>"), _("<branch>"));
463                 fprintf(stderr, "\n");
464                 fprintf_ln(stderr, _("If you wish to set tracking information for this branch you can do so with:"));
465                 fprintf(stderr, "\n");
466                 fprintf_ln(stderr, "    git branch --set-upstream-to=%s/%s %s\n",
467                                 remote_name, _("<branch>"), curr_branch->name);
468         } else
469                 fprintf_ln(stderr, _("Your configuration specifies to merge with the ref '%s'\n"
470                         "from the remote, but no such ref was fetched."),
471                         *curr_branch->merge_name);
472         exit(1);
473 }
474
475 /**
476  * Parses argv into [<repo> [<refspecs>...]], returning their values in `repo`
477  * as a string and `refspecs` as a null-terminated array of strings. If `repo`
478  * is not provided in argv, it is set to NULL.
479  */
480 static void parse_repo_refspecs(int argc, const char **argv, const char **repo,
481                 const char ***refspecs)
482 {
483         if (argc > 0) {
484                 *repo = *argv++;
485                 argc--;
486         } else
487                 *repo = NULL;
488         *refspecs = argv;
489 }
490
491 /**
492  * Runs git-fetch, returning its exit status. `repo` and `refspecs` are the
493  * repository and refspecs to fetch, or NULL if they are not provided.
494  */
495 static int run_fetch(const char *repo, const char **refspecs)
496 {
497         struct argv_array args = ARGV_ARRAY_INIT;
498         int ret;
499
500         argv_array_pushl(&args, "fetch", "--update-head-ok", NULL);
501
502         /* Shared options */
503         argv_push_verbosity(&args);
504         if (opt_progress)
505                 argv_array_push(&args, opt_progress);
506
507         /* Options passed to git-fetch */
508         if (opt_all)
509                 argv_array_push(&args, opt_all);
510         if (opt_append)
511                 argv_array_push(&args, opt_append);
512         if (opt_upload_pack)
513                 argv_array_push(&args, opt_upload_pack);
514         argv_push_force(&args);
515         if (opt_tags)
516                 argv_array_push(&args, opt_tags);
517         if (opt_prune)
518                 argv_array_push(&args, opt_prune);
519         if (recurse_submodules != RECURSE_SUBMODULES_DEFAULT)
520                 switch (recurse_submodules) {
521                 case RECURSE_SUBMODULES_ON:
522                         argv_array_push(&args, "--recurse-submodules=on");
523                         break;
524                 case RECURSE_SUBMODULES_OFF:
525                         argv_array_push(&args, "--recurse-submodules=no");
526                         break;
527                 case RECURSE_SUBMODULES_ON_DEMAND:
528                         argv_array_push(&args, "--recurse-submodules=on-demand");
529                         break;
530                 default:
531                         BUG("submodule recursion option not understood");
532                 }
533         if (max_children)
534                 argv_array_push(&args, max_children);
535         if (opt_dry_run)
536                 argv_array_push(&args, "--dry-run");
537         if (opt_keep)
538                 argv_array_push(&args, opt_keep);
539         if (opt_depth)
540                 argv_array_push(&args, opt_depth);
541         if (opt_unshallow)
542                 argv_array_push(&args, opt_unshallow);
543         if (opt_update_shallow)
544                 argv_array_push(&args, opt_update_shallow);
545         if (opt_refmap)
546                 argv_array_push(&args, opt_refmap);
547         if (opt_ipv4)
548                 argv_array_push(&args, opt_ipv4);
549         if (opt_ipv6)
550                 argv_array_push(&args, opt_ipv6);
551
552         if (repo) {
553                 argv_array_push(&args, repo);
554                 argv_array_pushv(&args, refspecs);
555         } else if (*refspecs)
556                 BUG("refspecs without repo?");
557         ret = run_command_v_opt(args.argv, RUN_GIT_CMD);
558         argv_array_clear(&args);
559         return ret;
560 }
561
562 /**
563  * "Pulls into void" by branching off merge_head.
564  */
565 static int pull_into_void(const struct object_id *merge_head,
566                 const struct object_id *curr_head)
567 {
568         if (opt_verify_signatures) {
569                 struct commit *commit;
570
571                 commit = lookup_commit(the_repository, merge_head);
572                 if (!commit)
573                         die(_("unable to access commit %s"),
574                             oid_to_hex(merge_head));
575
576                 verify_merge_signature(commit, opt_verbosity);
577         }
578
579         /*
580          * Two-way merge: we treat the index as based on an empty tree,
581          * and try to fast-forward to HEAD. This ensures we will not lose
582          * index/worktree changes that the user already made on the unborn
583          * branch.
584          */
585         if (checkout_fast_forward(the_repository,
586                                   the_hash_algo->empty_tree,
587                                   merge_head, 0))
588                 return 1;
589
590         if (update_ref("initial pull", "HEAD", merge_head, curr_head, 0, UPDATE_REFS_DIE_ON_ERR))
591                 return 1;
592
593         return 0;
594 }
595
596 static int rebase_submodules(void)
597 {
598         struct child_process cp = CHILD_PROCESS_INIT;
599
600         cp.git_cmd = 1;
601         cp.no_stdin = 1;
602         argv_array_pushl(&cp.args, "submodule", "update",
603                                    "--recursive", "--rebase", NULL);
604         argv_push_verbosity(&cp.args);
605
606         return run_command(&cp);
607 }
608
609 static int update_submodules(void)
610 {
611         struct child_process cp = CHILD_PROCESS_INIT;
612
613         cp.git_cmd = 1;
614         cp.no_stdin = 1;
615         argv_array_pushl(&cp.args, "submodule", "update",
616                                    "--recursive", "--checkout", NULL);
617         argv_push_verbosity(&cp.args);
618
619         return run_command(&cp);
620 }
621
622 /**
623  * Runs git-merge, returning its exit status.
624  */
625 static int run_merge(void)
626 {
627         int ret;
628         struct argv_array args = ARGV_ARRAY_INIT;
629
630         argv_array_pushl(&args, "merge", NULL);
631
632         /* Shared options */
633         argv_push_verbosity(&args);
634         if (opt_progress)
635                 argv_array_push(&args, opt_progress);
636
637         /* Options passed to git-merge */
638         if (opt_diffstat)
639                 argv_array_push(&args, opt_diffstat);
640         if (opt_log)
641                 argv_array_push(&args, opt_log);
642         if (opt_signoff)
643                 argv_array_push(&args, opt_signoff);
644         if (opt_squash)
645                 argv_array_push(&args, opt_squash);
646         if (opt_commit)
647                 argv_array_push(&args, opt_commit);
648         if (opt_edit)
649                 argv_array_push(&args, opt_edit);
650         if (cleanup_arg)
651                 argv_array_pushf(&args, "--cleanup=%s", cleanup_arg);
652         if (opt_ff)
653                 argv_array_push(&args, opt_ff);
654         if (opt_verify_signatures)
655                 argv_array_push(&args, opt_verify_signatures);
656         argv_array_pushv(&args, opt_strategies.argv);
657         argv_array_pushv(&args, opt_strategy_opts.argv);
658         if (opt_gpg_sign)
659                 argv_array_push(&args, opt_gpg_sign);
660         if (opt_allow_unrelated_histories > 0)
661                 argv_array_push(&args, "--allow-unrelated-histories");
662
663         argv_array_push(&args, "FETCH_HEAD");
664         ret = run_command_v_opt(args.argv, RUN_GIT_CMD);
665         argv_array_clear(&args);
666         return ret;
667 }
668
669 /**
670  * Returns remote's upstream branch for the current branch. If remote is NULL,
671  * the current branch's configured default remote is used. Returns NULL if
672  * `remote` does not name a valid remote, HEAD does not point to a branch,
673  * remote is not the branch's configured remote or the branch does not have any
674  * configured upstream branch.
675  */
676 static const char *get_upstream_branch(const char *remote)
677 {
678         struct remote *rm;
679         struct branch *curr_branch;
680         const char *curr_branch_remote;
681
682         rm = remote_get(remote);
683         if (!rm)
684                 return NULL;
685
686         curr_branch = branch_get("HEAD");
687         if (!curr_branch)
688                 return NULL;
689
690         curr_branch_remote = remote_for_branch(curr_branch, NULL);
691         assert(curr_branch_remote);
692
693         if (strcmp(curr_branch_remote, rm->name))
694                 return NULL;
695
696         return branch_get_upstream(curr_branch, NULL);
697 }
698
699 /**
700  * Derives the remote-tracking branch from the remote and refspec.
701  *
702  * FIXME: The current implementation assumes the default mapping of
703  * refs/heads/<branch_name> to refs/remotes/<remote_name>/<branch_name>.
704  */
705 static const char *get_tracking_branch(const char *remote, const char *refspec)
706 {
707         struct refspec_item spec;
708         const char *spec_src;
709         const char *merge_branch;
710
711         refspec_item_init_or_die(&spec, refspec, REFSPEC_FETCH);
712         spec_src = spec.src;
713         if (!*spec_src || !strcmp(spec_src, "HEAD"))
714                 spec_src = "HEAD";
715         else if (skip_prefix(spec_src, "heads/", &spec_src))
716                 ;
717         else if (skip_prefix(spec_src, "refs/heads/", &spec_src))
718                 ;
719         else if (starts_with(spec_src, "refs/") ||
720                 starts_with(spec_src, "tags/") ||
721                 starts_with(spec_src, "remotes/"))
722                 spec_src = "";
723
724         if (*spec_src) {
725                 if (!strcmp(remote, "."))
726                         merge_branch = mkpath("refs/heads/%s", spec_src);
727                 else
728                         merge_branch = mkpath("refs/remotes/%s/%s", remote, spec_src);
729         } else
730                 merge_branch = NULL;
731
732         refspec_item_clear(&spec);
733         return merge_branch;
734 }
735
736 /**
737  * Given the repo and refspecs, sets fork_point to the point at which the
738  * current branch forked from its remote-tracking branch. Returns 0 on success,
739  * -1 on failure.
740  */
741 static int get_rebase_fork_point(struct object_id *fork_point, const char *repo,
742                 const char *refspec)
743 {
744         int ret;
745         struct branch *curr_branch;
746         const char *remote_branch;
747         struct child_process cp = CHILD_PROCESS_INIT;
748         struct strbuf sb = STRBUF_INIT;
749
750         curr_branch = branch_get("HEAD");
751         if (!curr_branch)
752                 return -1;
753
754         if (refspec)
755                 remote_branch = get_tracking_branch(repo, refspec);
756         else
757                 remote_branch = get_upstream_branch(repo);
758
759         if (!remote_branch)
760                 return -1;
761
762         argv_array_pushl(&cp.args, "merge-base", "--fork-point",
763                         remote_branch, curr_branch->name, NULL);
764         cp.no_stdin = 1;
765         cp.no_stderr = 1;
766         cp.git_cmd = 1;
767
768         ret = capture_command(&cp, &sb, GIT_SHA1_HEXSZ);
769         if (ret)
770                 goto cleanup;
771
772         ret = get_oid_hex(sb.buf, fork_point);
773         if (ret)
774                 goto cleanup;
775
776 cleanup:
777         strbuf_release(&sb);
778         return ret ? -1 : 0;
779 }
780
781 /**
782  * Sets merge_base to the octopus merge base of curr_head, merge_head and
783  * fork_point. Returns 0 if a merge base is found, 1 otherwise.
784  */
785 static int get_octopus_merge_base(struct object_id *merge_base,
786                 const struct object_id *curr_head,
787                 const struct object_id *merge_head,
788                 const struct object_id *fork_point)
789 {
790         struct commit_list *revs = NULL, *result;
791
792         commit_list_insert(lookup_commit_reference(the_repository, curr_head),
793                            &revs);
794         commit_list_insert(lookup_commit_reference(the_repository, merge_head),
795                            &revs);
796         if (!is_null_oid(fork_point))
797                 commit_list_insert(lookup_commit_reference(the_repository, fork_point),
798                                    &revs);
799
800         result = get_octopus_merge_bases(revs);
801         free_commit_list(revs);
802         reduce_heads_replace(&result);
803
804         if (!result)
805                 return 1;
806
807         oidcpy(merge_base, &result->item->object.oid);
808         free_commit_list(result);
809         return 0;
810 }
811
812 /**
813  * Given the current HEAD SHA1, the merge head returned from git-fetch and the
814  * fork point calculated by get_rebase_fork_point(), runs git-rebase with the
815  * appropriate arguments and returns its exit status.
816  */
817 static int run_rebase(const struct object_id *curr_head,
818                 const struct object_id *merge_head,
819                 const struct object_id *fork_point)
820 {
821         int ret;
822         struct object_id oct_merge_base;
823         struct argv_array args = ARGV_ARRAY_INIT;
824
825         if (!get_octopus_merge_base(&oct_merge_base, curr_head, merge_head, fork_point))
826                 if (!is_null_oid(fork_point) && oideq(&oct_merge_base, fork_point))
827                         fork_point = NULL;
828
829         argv_array_push(&args, "rebase");
830
831         /* Shared options */
832         argv_push_verbosity(&args);
833
834         /* Options passed to git-rebase */
835         if (opt_rebase == REBASE_MERGES)
836                 argv_array_push(&args, "--rebase-merges");
837         else if (opt_rebase == REBASE_PRESERVE)
838                 argv_array_push(&args, "--preserve-merges");
839         else if (opt_rebase == REBASE_INTERACTIVE)
840                 argv_array_push(&args, "--interactive");
841         if (opt_diffstat)
842                 argv_array_push(&args, opt_diffstat);
843         argv_array_pushv(&args, opt_strategies.argv);
844         argv_array_pushv(&args, opt_strategy_opts.argv);
845         if (opt_gpg_sign)
846                 argv_array_push(&args, opt_gpg_sign);
847         if (opt_autostash == 0)
848                 argv_array_push(&args, "--no-autostash");
849         else if (opt_autostash == 1)
850                 argv_array_push(&args, "--autostash");
851         if (opt_verify_signatures &&
852             !strcmp(opt_verify_signatures, "--verify-signatures"))
853                 warning(_("ignoring --verify-signatures for rebase"));
854
855         argv_array_push(&args, "--onto");
856         argv_array_push(&args, oid_to_hex(merge_head));
857
858         if (fork_point && !is_null_oid(fork_point))
859                 argv_array_push(&args, oid_to_hex(fork_point));
860         else
861                 argv_array_push(&args, oid_to_hex(merge_head));
862
863         ret = run_command_v_opt(args.argv, RUN_GIT_CMD);
864         argv_array_clear(&args);
865         return ret;
866 }
867
868 int cmd_pull(int argc, const char **argv, const char *prefix)
869 {
870         const char *repo, **refspecs;
871         struct oid_array merge_heads = OID_ARRAY_INIT;
872         struct object_id orig_head, curr_head;
873         struct object_id rebase_fork_point;
874         int autostash;
875
876         if (!getenv("GIT_REFLOG_ACTION"))
877                 set_reflog_message(argc, argv);
878
879         git_config(git_pull_config, NULL);
880
881         argc = parse_options(argc, argv, prefix, pull_options, pull_usage, 0);
882
883         if (cleanup_arg)
884                 /*
885                  * this only checks the validity of cleanup_arg; we don't need
886                  * a valid value for use_editor
887                  */
888                 get_cleanup_mode(cleanup_arg, 0);
889
890         parse_repo_refspecs(argc, argv, &repo, &refspecs);
891
892         if (!opt_ff)
893                 opt_ff = xstrdup_or_null(config_get_ff());
894
895         if (opt_rebase < 0)
896                 opt_rebase = config_get_rebase();
897
898         if (read_cache_unmerged())
899                 die_resolve_conflict("pull");
900
901         if (file_exists(git_path_merge_head(the_repository)))
902                 die_conclude_merge();
903
904         if (get_oid("HEAD", &orig_head))
905                 oidclr(&orig_head);
906
907         if (!opt_rebase && opt_autostash != -1)
908                 die(_("--[no-]autostash option is only valid with --rebase."));
909
910         autostash = config_autostash;
911         if (opt_rebase) {
912                 if (opt_autostash != -1)
913                         autostash = opt_autostash;
914
915                 if (is_null_oid(&orig_head) && !is_cache_unborn())
916                         die(_("Updating an unborn branch with changes added to the index."));
917
918                 if (!autostash)
919                         require_clean_work_tree(the_repository,
920                                 N_("pull with rebase"),
921                                 _("please commit or stash them."), 1, 0);
922
923                 if (get_rebase_fork_point(&rebase_fork_point, repo, *refspecs))
924                         oidclr(&rebase_fork_point);
925         }
926
927         if (run_fetch(repo, refspecs))
928                 return 1;
929
930         if (opt_dry_run)
931                 return 0;
932
933         if (get_oid("HEAD", &curr_head))
934                 oidclr(&curr_head);
935
936         if (!is_null_oid(&orig_head) && !is_null_oid(&curr_head) &&
937                         !oideq(&orig_head, &curr_head)) {
938                 /*
939                  * The fetch involved updating the current branch.
940                  *
941                  * The working tree and the index file are still based on
942                  * orig_head commit, but we are merging into curr_head.
943                  * Update the working tree to match curr_head.
944                  */
945
946                 warning(_("fetch updated the current branch head.\n"
947                         "fast-forwarding your working tree from\n"
948                         "commit %s."), oid_to_hex(&orig_head));
949
950                 if (checkout_fast_forward(the_repository, &orig_head,
951                                           &curr_head, 0))
952                         die(_("Cannot fast-forward your working tree.\n"
953                                 "After making sure that you saved anything precious from\n"
954                                 "$ git diff %s\n"
955                                 "output, run\n"
956                                 "$ git reset --hard\n"
957                                 "to recover."), oid_to_hex(&orig_head));
958         }
959
960         get_merge_heads(&merge_heads);
961
962         if (!merge_heads.nr)
963                 die_no_merge_candidates(repo, refspecs);
964
965         if (is_null_oid(&orig_head)) {
966                 if (merge_heads.nr > 1)
967                         die(_("Cannot merge multiple branches into empty head."));
968                 return pull_into_void(merge_heads.oid, &curr_head);
969         }
970         if (opt_rebase && merge_heads.nr > 1)
971                 die(_("Cannot rebase onto multiple branches."));
972
973         if (opt_rebase) {
974                 int ret = 0;
975                 if ((recurse_submodules == RECURSE_SUBMODULES_ON ||
976                      recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND) &&
977                     submodule_touches_in_range(the_repository, &rebase_fork_point, &curr_head))
978                         die(_("cannot rebase with locally recorded submodule modifications"));
979                 if (!autostash) {
980                         struct commit_list *list = NULL;
981                         struct commit *merge_head, *head;
982
983                         head = lookup_commit_reference(the_repository,
984                                                        &orig_head);
985                         commit_list_insert(head, &list);
986                         merge_head = lookup_commit_reference(the_repository,
987                                                              &merge_heads.oid[0]);
988                         if (is_descendant_of(merge_head, list)) {
989                                 /* we can fast-forward this without invoking rebase */
990                                 opt_ff = "--ff-only";
991                                 ret = run_merge();
992                         }
993                 }
994                 ret = run_rebase(&curr_head, merge_heads.oid, &rebase_fork_point);
995
996                 if (!ret && (recurse_submodules == RECURSE_SUBMODULES_ON ||
997                              recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND))
998                         ret = rebase_submodules();
999
1000                 return ret;
1001         } else {
1002                 int ret = run_merge();
1003                 if (!ret && (recurse_submodules == RECURSE_SUBMODULES_ON ||
1004                              recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND))
1005                         ret = update_submodules();
1006                 return ret;
1007         }
1008 }