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