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