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