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