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