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