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