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