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