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