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