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