builtin / pull.con commit Merge branch 'bb/ssh-key-files' of git-gui into bb/git-gui-ssh-key-files (2e2f028)
   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        argv_push_verbosity(&cp.args);
 578
 579        return run_command(&cp);
 580}
 581
 582static int update_submodules(void)
 583{
 584        struct child_process cp = CHILD_PROCESS_INIT;
 585
 586        cp.git_cmd = 1;
 587        cp.no_stdin = 1;
 588        argv_array_pushl(&cp.args, "submodule", "update",
 589                                   "--recursive", "--checkout", NULL);
 590        argv_push_verbosity(&cp.args);
 591
 592        return run_command(&cp);
 593}
 594
 595/**
 596 * Runs git-merge, returning its exit status.
 597 */
 598static int run_merge(void)
 599{
 600        int ret;
 601        struct argv_array args = ARGV_ARRAY_INIT;
 602
 603        argv_array_pushl(&args, "merge", NULL);
 604
 605        /* Shared options */
 606        argv_push_verbosity(&args);
 607        if (opt_progress)
 608                argv_array_push(&args, opt_progress);
 609
 610        /* Options passed to git-merge */
 611        if (opt_diffstat)
 612                argv_array_push(&args, opt_diffstat);
 613        if (opt_log)
 614                argv_array_push(&args, opt_log);
 615        if (opt_signoff)
 616                argv_array_push(&args, opt_signoff);
 617        if (opt_squash)
 618                argv_array_push(&args, opt_squash);
 619        if (opt_commit)
 620                argv_array_push(&args, opt_commit);
 621        if (opt_edit)
 622                argv_array_push(&args, opt_edit);
 623        if (opt_ff)
 624                argv_array_push(&args, opt_ff);
 625        if (opt_verify_signatures)
 626                argv_array_push(&args, opt_verify_signatures);
 627        argv_array_pushv(&args, opt_strategies.argv);
 628        argv_array_pushv(&args, opt_strategy_opts.argv);
 629        if (opt_gpg_sign)
 630                argv_array_push(&args, opt_gpg_sign);
 631        if (opt_allow_unrelated_histories > 0)
 632                argv_array_push(&args, "--allow-unrelated-histories");
 633
 634        argv_array_push(&args, "FETCH_HEAD");
 635        ret = run_command_v_opt(args.argv, RUN_GIT_CMD);
 636        argv_array_clear(&args);
 637        return ret;
 638}
 639
 640/**
 641 * Returns remote's upstream branch for the current branch. If remote is NULL,
 642 * the current branch's configured default remote is used. Returns NULL if
 643 * `remote` does not name a valid remote, HEAD does not point to a branch,
 644 * remote is not the branch's configured remote or the branch does not have any
 645 * configured upstream branch.
 646 */
 647static const char *get_upstream_branch(const char *remote)
 648{
 649        struct remote *rm;
 650        struct branch *curr_branch;
 651        const char *curr_branch_remote;
 652
 653        rm = remote_get(remote);
 654        if (!rm)
 655                return NULL;
 656
 657        curr_branch = branch_get("HEAD");
 658        if (!curr_branch)
 659                return NULL;
 660
 661        curr_branch_remote = remote_for_branch(curr_branch, NULL);
 662        assert(curr_branch_remote);
 663
 664        if (strcmp(curr_branch_remote, rm->name))
 665                return NULL;
 666
 667        return branch_get_upstream(curr_branch, NULL);
 668}
 669
 670/**
 671 * Derives the remote tracking branch from the remote and refspec.
 672 *
 673 * FIXME: The current implementation assumes the default mapping of
 674 * refs/heads/<branch_name> to refs/remotes/<remote_name>/<branch_name>.
 675 */
 676static const char *get_tracking_branch(const char *remote, const char *refspec)
 677{
 678        struct refspec *spec;
 679        const char *spec_src;
 680        const char *merge_branch;
 681
 682        spec = parse_fetch_refspec(1, &refspec);
 683        spec_src = spec->src;
 684        if (!*spec_src || !strcmp(spec_src, "HEAD"))
 685                spec_src = "HEAD";
 686        else if (skip_prefix(spec_src, "heads/", &spec_src))
 687                ;
 688        else if (skip_prefix(spec_src, "refs/heads/", &spec_src))
 689                ;
 690        else if (starts_with(spec_src, "refs/") ||
 691                starts_with(spec_src, "tags/") ||
 692                starts_with(spec_src, "remotes/"))
 693                spec_src = "";
 694
 695        if (*spec_src) {
 696                if (!strcmp(remote, "."))
 697                        merge_branch = mkpath("refs/heads/%s", spec_src);
 698                else
 699                        merge_branch = mkpath("refs/remotes/%s/%s", remote, spec_src);
 700        } else
 701                merge_branch = NULL;
 702
 703        free_refspec(1, spec);
 704        return merge_branch;
 705}
 706
 707/**
 708 * Given the repo and refspecs, sets fork_point to the point at which the
 709 * current branch forked from its remote tracking branch. Returns 0 on success,
 710 * -1 on failure.
 711 */
 712static int get_rebase_fork_point(struct object_id *fork_point, const char *repo,
 713                const char *refspec)
 714{
 715        int ret;
 716        struct branch *curr_branch;
 717        const char *remote_branch;
 718        struct child_process cp = CHILD_PROCESS_INIT;
 719        struct strbuf sb = STRBUF_INIT;
 720
 721        curr_branch = branch_get("HEAD");
 722        if (!curr_branch)
 723                return -1;
 724
 725        if (refspec)
 726                remote_branch = get_tracking_branch(repo, refspec);
 727        else
 728                remote_branch = get_upstream_branch(repo);
 729
 730        if (!remote_branch)
 731                return -1;
 732
 733        argv_array_pushl(&cp.args, "merge-base", "--fork-point",
 734                        remote_branch, curr_branch->name, NULL);
 735        cp.no_stdin = 1;
 736        cp.no_stderr = 1;
 737        cp.git_cmd = 1;
 738
 739        ret = capture_command(&cp, &sb, GIT_SHA1_HEXSZ);
 740        if (ret)
 741                goto cleanup;
 742
 743        ret = get_oid_hex(sb.buf, fork_point);
 744        if (ret)
 745                goto cleanup;
 746
 747cleanup:
 748        strbuf_release(&sb);
 749        return ret ? -1 : 0;
 750}
 751
 752/**
 753 * Sets merge_base to the octopus merge base of curr_head, merge_head and
 754 * fork_point. Returns 0 if a merge base is found, 1 otherwise.
 755 */
 756static int get_octopus_merge_base(struct object_id *merge_base,
 757                const struct object_id *curr_head,
 758                const struct object_id *merge_head,
 759                const struct object_id *fork_point)
 760{
 761        struct commit_list *revs = NULL, *result;
 762
 763        commit_list_insert(lookup_commit_reference(curr_head), &revs);
 764        commit_list_insert(lookup_commit_reference(merge_head), &revs);
 765        if (!is_null_oid(fork_point))
 766                commit_list_insert(lookup_commit_reference(fork_point), &revs);
 767
 768        result = get_octopus_merge_bases(revs);
 769        free_commit_list(revs);
 770        reduce_heads_replace(&result);
 771
 772        if (!result)
 773                return 1;
 774
 775        oidcpy(merge_base, &result->item->object.oid);
 776        free_commit_list(result);
 777        return 0;
 778}
 779
 780/**
 781 * Given the current HEAD SHA1, the merge head returned from git-fetch and the
 782 * fork point calculated by get_rebase_fork_point(), runs git-rebase with the
 783 * appropriate arguments and returns its exit status.
 784 */
 785static int run_rebase(const struct object_id *curr_head,
 786                const struct object_id *merge_head,
 787                const struct object_id *fork_point)
 788{
 789        int ret;
 790        struct object_id oct_merge_base;
 791        struct argv_array args = ARGV_ARRAY_INIT;
 792
 793        if (!get_octopus_merge_base(&oct_merge_base, curr_head, merge_head, fork_point))
 794                if (!is_null_oid(fork_point) && !oidcmp(&oct_merge_base, fork_point))
 795                        fork_point = NULL;
 796
 797        argv_array_push(&args, "rebase");
 798
 799        /* Shared options */
 800        argv_push_verbosity(&args);
 801
 802        /* Options passed to git-rebase */
 803        if (opt_rebase == REBASE_PRESERVE)
 804                argv_array_push(&args, "--preserve-merges");
 805        else if (opt_rebase == REBASE_INTERACTIVE)
 806                argv_array_push(&args, "--interactive");
 807        if (opt_diffstat)
 808                argv_array_push(&args, opt_diffstat);
 809        argv_array_pushv(&args, opt_strategies.argv);
 810        argv_array_pushv(&args, opt_strategy_opts.argv);
 811        if (opt_gpg_sign)
 812                argv_array_push(&args, opt_gpg_sign);
 813        if (opt_autostash == 0)
 814                argv_array_push(&args, "--no-autostash");
 815        else if (opt_autostash == 1)
 816                argv_array_push(&args, "--autostash");
 817        if (opt_verify_signatures &&
 818            !strcmp(opt_verify_signatures, "--verify-signatures"))
 819                warning(_("ignoring --verify-signatures for rebase"));
 820
 821        argv_array_push(&args, "--onto");
 822        argv_array_push(&args, oid_to_hex(merge_head));
 823
 824        if (fork_point && !is_null_oid(fork_point))
 825                argv_array_push(&args, oid_to_hex(fork_point));
 826        else
 827                argv_array_push(&args, oid_to_hex(merge_head));
 828
 829        ret = run_command_v_opt(args.argv, RUN_GIT_CMD);
 830        argv_array_clear(&args);
 831        return ret;
 832}
 833
 834int cmd_pull(int argc, const char **argv, const char *prefix)
 835{
 836        const char *repo, **refspecs;
 837        struct oid_array merge_heads = OID_ARRAY_INIT;
 838        struct object_id orig_head, curr_head;
 839        struct object_id rebase_fork_point;
 840        int autostash;
 841
 842        if (!getenv("GIT_REFLOG_ACTION"))
 843                set_reflog_message(argc, argv);
 844
 845        git_config(git_pull_config, NULL);
 846
 847        argc = parse_options(argc, argv, prefix, pull_options, pull_usage, 0);
 848
 849        parse_repo_refspecs(argc, argv, &repo, &refspecs);
 850
 851        if (!opt_ff)
 852                opt_ff = xstrdup_or_null(config_get_ff());
 853
 854        if (opt_rebase < 0)
 855                opt_rebase = config_get_rebase();
 856
 857        if (read_cache_unmerged())
 858                die_resolve_conflict("pull");
 859
 860        if (file_exists(git_path_merge_head()))
 861                die_conclude_merge();
 862
 863        if (get_oid("HEAD", &orig_head))
 864                oidclr(&orig_head);
 865
 866        if (!opt_rebase && opt_autostash != -1)
 867                die(_("--[no-]autostash option is only valid with --rebase."));
 868
 869        autostash = config_autostash;
 870        if (opt_rebase) {
 871                if (opt_autostash != -1)
 872                        autostash = opt_autostash;
 873
 874                if (is_null_oid(&orig_head) && !is_cache_unborn())
 875                        die(_("Updating an unborn branch with changes added to the index."));
 876
 877                if (!autostash)
 878                        require_clean_work_tree(N_("pull with rebase"),
 879                                _("please commit or stash them."), 1, 0);
 880
 881                if (get_rebase_fork_point(&rebase_fork_point, repo, *refspecs))
 882                        oidclr(&rebase_fork_point);
 883        }
 884
 885        if (run_fetch(repo, refspecs))
 886                return 1;
 887
 888        if (opt_dry_run)
 889                return 0;
 890
 891        if (get_oid("HEAD", &curr_head))
 892                oidclr(&curr_head);
 893
 894        if (!is_null_oid(&orig_head) && !is_null_oid(&curr_head) &&
 895                        oidcmp(&orig_head, &curr_head)) {
 896                /*
 897                 * The fetch involved updating the current branch.
 898                 *
 899                 * The working tree and the index file are still based on
 900                 * orig_head commit, but we are merging into curr_head.
 901                 * Update the working tree to match curr_head.
 902                 */
 903
 904                warning(_("fetch updated the current branch head.\n"
 905                        "fast-forwarding your working tree from\n"
 906                        "commit %s."), oid_to_hex(&orig_head));
 907
 908                if (checkout_fast_forward(&orig_head, &curr_head, 0))
 909                        die(_("Cannot fast-forward your working tree.\n"
 910                                "After making sure that you saved anything precious from\n"
 911                                "$ git diff %s\n"
 912                                "output, run\n"
 913                                "$ git reset --hard\n"
 914                                "to recover."), oid_to_hex(&orig_head));
 915        }
 916
 917        get_merge_heads(&merge_heads);
 918
 919        if (!merge_heads.nr)
 920                die_no_merge_candidates(repo, refspecs);
 921
 922        if (is_null_oid(&orig_head)) {
 923                if (merge_heads.nr > 1)
 924                        die(_("Cannot merge multiple branches into empty head."));
 925                return pull_into_void(merge_heads.oid, &curr_head);
 926        }
 927        if (opt_rebase && merge_heads.nr > 1)
 928                die(_("Cannot rebase onto multiple branches."));
 929
 930        if (opt_rebase) {
 931                int ret = 0;
 932                if ((recurse_submodules == RECURSE_SUBMODULES_ON ||
 933                     recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND) &&
 934                    submodule_touches_in_range(&rebase_fork_point, &curr_head))
 935                        die(_("cannot rebase with locally recorded submodule modifications"));
 936                if (!autostash) {
 937                        struct commit_list *list = NULL;
 938                        struct commit *merge_head, *head;
 939
 940                        head = lookup_commit_reference(&orig_head);
 941                        commit_list_insert(head, &list);
 942                        merge_head = lookup_commit_reference(&merge_heads.oid[0]);
 943                        if (is_descendant_of(merge_head, list)) {
 944                                /* we can fast-forward this without invoking rebase */
 945                                opt_ff = "--ff-only";
 946                                ret = run_merge();
 947                        }
 948                }
 949                ret = run_rebase(&curr_head, merge_heads.oid, &rebase_fork_point);
 950
 951                if (!ret && (recurse_submodules == RECURSE_SUBMODULES_ON ||
 952                             recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND))
 953                        ret = rebase_submodules();
 954
 955                return ret;
 956        } else {
 957                int ret = run_merge();
 958                if (!ret && (recurse_submodules == RECURSE_SUBMODULES_ON ||
 959                             recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND))
 960                        ret = update_submodules();
 961                return ret;
 962        }
 963}