builtin / rebase.con commit built-in rebase --skip/--abort: clean up stale .git/<name> files (5aec927)
   1/*
   2 * "git rebase" builtin command
   3 *
   4 * Copyright (c) 2018 Pratik Karki
   5 */
   6
   7#include "builtin.h"
   8#include "run-command.h"
   9#include "exec-cmd.h"
  10#include "argv-array.h"
  11#include "dir.h"
  12#include "packfile.h"
  13#include "refs.h"
  14#include "quote.h"
  15#include "config.h"
  16#include "cache-tree.h"
  17#include "unpack-trees.h"
  18#include "lockfile.h"
  19#include "parse-options.h"
  20#include "commit.h"
  21#include "diff.h"
  22#include "wt-status.h"
  23#include "revision.h"
  24#include "commit-reach.h"
  25#include "rerere.h"
  26#include "branch.h"
  27
  28static char const * const builtin_rebase_usage[] = {
  29        N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
  30                "[<upstream>] [<branch>]"),
  31        N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
  32                "--root [<branch>]"),
  33        N_("git rebase --continue | --abort | --skip | --edit-todo"),
  34        NULL
  35};
  36
  37static GIT_PATH_FUNC(apply_dir, "rebase-apply")
  38static GIT_PATH_FUNC(merge_dir, "rebase-merge")
  39
  40enum rebase_type {
  41        REBASE_UNSPECIFIED = -1,
  42        REBASE_AM,
  43        REBASE_MERGE,
  44        REBASE_INTERACTIVE,
  45        REBASE_PRESERVE_MERGES
  46};
  47
  48static int use_builtin_rebase(void)
  49{
  50        struct child_process cp = CHILD_PROCESS_INIT;
  51        struct strbuf out = STRBUF_INIT;
  52        int ret;
  53
  54        argv_array_pushl(&cp.args,
  55                         "config", "--bool", "rebase.usebuiltin", NULL);
  56        cp.git_cmd = 1;
  57        if (capture_command(&cp, &out, 6)) {
  58                strbuf_release(&out);
  59                return 1;
  60        }
  61
  62        strbuf_trim(&out);
  63        ret = !strcmp("true", out.buf);
  64        strbuf_release(&out);
  65        return ret;
  66}
  67
  68struct rebase_options {
  69        enum rebase_type type;
  70        const char *state_dir;
  71        struct commit *upstream;
  72        const char *upstream_name;
  73        const char *upstream_arg;
  74        char *head_name;
  75        struct object_id orig_head;
  76        struct commit *onto;
  77        const char *onto_name;
  78        const char *revisions;
  79        const char *switch_to;
  80        int root;
  81        struct object_id *squash_onto;
  82        struct commit *restrict_revision;
  83        int dont_finish_rebase;
  84        enum {
  85                REBASE_NO_QUIET = 1<<0,
  86                REBASE_VERBOSE = 1<<1,
  87                REBASE_DIFFSTAT = 1<<2,
  88                REBASE_FORCE = 1<<3,
  89                REBASE_INTERACTIVE_EXPLICIT = 1<<4,
  90        } flags;
  91        struct strbuf git_am_opt;
  92        const char *action;
  93        int signoff;
  94        int allow_rerere_autoupdate;
  95        int keep_empty;
  96        int autosquash;
  97        char *gpg_sign_opt;
  98        int autostash;
  99        char *cmd;
 100        int allow_empty_message;
 101        int rebase_merges, rebase_cousins;
 102        char *strategy, *strategy_opts;
 103        struct strbuf git_format_patch_opt;
 104};
 105
 106static int is_interactive(struct rebase_options *opts)
 107{
 108        return opts->type == REBASE_INTERACTIVE ||
 109                opts->type == REBASE_PRESERVE_MERGES;
 110}
 111
 112static void imply_interactive(struct rebase_options *opts, const char *option)
 113{
 114        switch (opts->type) {
 115        case REBASE_AM:
 116                die(_("%s requires an interactive rebase"), option);
 117                break;
 118        case REBASE_INTERACTIVE:
 119        case REBASE_PRESERVE_MERGES:
 120                break;
 121        case REBASE_MERGE:
 122                /* we silently *upgrade* --merge to --interactive if needed */
 123        default:
 124                opts->type = REBASE_INTERACTIVE; /* implied */
 125                break;
 126        }
 127}
 128
 129/* Returns the filename prefixed by the state_dir */
 130static const char *state_dir_path(const char *filename, struct rebase_options *opts)
 131{
 132        static struct strbuf path = STRBUF_INIT;
 133        static size_t prefix_len;
 134
 135        if (!prefix_len) {
 136                strbuf_addf(&path, "%s/", opts->state_dir);
 137                prefix_len = path.len;
 138        }
 139
 140        strbuf_setlen(&path, prefix_len);
 141        strbuf_addstr(&path, filename);
 142        return path.buf;
 143}
 144
 145/* Read one file, then strip line endings */
 146static int read_one(const char *path, struct strbuf *buf)
 147{
 148        if (strbuf_read_file(buf, path, 0) < 0)
 149                return error_errno(_("could not read '%s'"), path);
 150        strbuf_trim_trailing_newline(buf);
 151        return 0;
 152}
 153
 154/* Initialize the rebase options from the state directory. */
 155static int read_basic_state(struct rebase_options *opts)
 156{
 157        struct strbuf head_name = STRBUF_INIT;
 158        struct strbuf buf = STRBUF_INIT;
 159        struct object_id oid;
 160
 161        if (read_one(state_dir_path("head-name", opts), &head_name) ||
 162            read_one(state_dir_path("onto", opts), &buf))
 163                return -1;
 164        opts->head_name = starts_with(head_name.buf, "refs/") ?
 165                xstrdup(head_name.buf) : NULL;
 166        strbuf_release(&head_name);
 167        if (get_oid(buf.buf, &oid))
 168                return error(_("could not get 'onto': '%s'"), buf.buf);
 169        opts->onto = lookup_commit_or_die(&oid, buf.buf);
 170
 171        /*
 172         * We always write to orig-head, but interactive rebase used to write to
 173         * head. Fall back to reading from head to cover for the case that the
 174         * user upgraded git with an ongoing interactive rebase.
 175         */
 176        strbuf_reset(&buf);
 177        if (file_exists(state_dir_path("orig-head", opts))) {
 178                if (read_one(state_dir_path("orig-head", opts), &buf))
 179                        return -1;
 180        } else if (read_one(state_dir_path("head", opts), &buf))
 181                return -1;
 182        if (get_oid(buf.buf, &opts->orig_head))
 183                return error(_("invalid orig-head: '%s'"), buf.buf);
 184
 185        strbuf_reset(&buf);
 186        if (read_one(state_dir_path("quiet", opts), &buf))
 187                return -1;
 188        if (buf.len)
 189                opts->flags &= ~REBASE_NO_QUIET;
 190        else
 191                opts->flags |= REBASE_NO_QUIET;
 192
 193        if (file_exists(state_dir_path("verbose", opts)))
 194                opts->flags |= REBASE_VERBOSE;
 195
 196        if (file_exists(state_dir_path("signoff", opts))) {
 197                opts->signoff = 1;
 198                opts->flags |= REBASE_FORCE;
 199        }
 200
 201        if (file_exists(state_dir_path("allow_rerere_autoupdate", opts))) {
 202                strbuf_reset(&buf);
 203                if (read_one(state_dir_path("allow_rerere_autoupdate", opts),
 204                            &buf))
 205                        return -1;
 206                if (!strcmp(buf.buf, "--rerere-autoupdate"))
 207                        opts->allow_rerere_autoupdate = 1;
 208                else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
 209                        opts->allow_rerere_autoupdate = 0;
 210                else
 211                        warning(_("ignoring invalid allow_rerere_autoupdate: "
 212                                  "'%s'"), buf.buf);
 213        } else
 214                opts->allow_rerere_autoupdate = -1;
 215
 216        if (file_exists(state_dir_path("gpg_sign_opt", opts))) {
 217                strbuf_reset(&buf);
 218                if (read_one(state_dir_path("gpg_sign_opt", opts),
 219                            &buf))
 220                        return -1;
 221                free(opts->gpg_sign_opt);
 222                opts->gpg_sign_opt = xstrdup(buf.buf);
 223        }
 224
 225        if (file_exists(state_dir_path("strategy", opts))) {
 226                strbuf_reset(&buf);
 227                if (read_one(state_dir_path("strategy", opts), &buf))
 228                        return -1;
 229                free(opts->strategy);
 230                opts->strategy = xstrdup(buf.buf);
 231        }
 232
 233        if (file_exists(state_dir_path("strategy_opts", opts))) {
 234                strbuf_reset(&buf);
 235                if (read_one(state_dir_path("strategy_opts", opts), &buf))
 236                        return -1;
 237                free(opts->strategy_opts);
 238                opts->strategy_opts = xstrdup(buf.buf);
 239        }
 240
 241        strbuf_release(&buf);
 242
 243        return 0;
 244}
 245
 246static int apply_autostash(struct rebase_options *opts)
 247{
 248        const char *path = state_dir_path("autostash", opts);
 249        struct strbuf autostash = STRBUF_INIT;
 250        struct child_process stash_apply = CHILD_PROCESS_INIT;
 251
 252        if (!file_exists(path))
 253                return 0;
 254
 255        if (read_one(path, &autostash))
 256                return error(_("Could not read '%s'"), path);
 257        /* Ensure that the hash is not mistaken for a number */
 258        strbuf_addstr(&autostash, "^0");
 259        argv_array_pushl(&stash_apply.args,
 260                         "stash", "apply", autostash.buf, NULL);
 261        stash_apply.git_cmd = 1;
 262        stash_apply.no_stderr = stash_apply.no_stdout =
 263                stash_apply.no_stdin = 1;
 264        if (!run_command(&stash_apply))
 265                printf(_("Applied autostash.\n"));
 266        else {
 267                struct argv_array args = ARGV_ARRAY_INIT;
 268                int res = 0;
 269
 270                argv_array_pushl(&args,
 271                                 "stash", "store", "-m", "autostash", "-q",
 272                                 autostash.buf, NULL);
 273                if (run_command_v_opt(args.argv, RUN_GIT_CMD))
 274                        res = error(_("Cannot store %s"), autostash.buf);
 275                argv_array_clear(&args);
 276                strbuf_release(&autostash);
 277                if (res)
 278                        return res;
 279
 280                fprintf(stderr,
 281                        _("Applying autostash resulted in conflicts.\n"
 282                          "Your changes are safe in the stash.\n"
 283                          "You can run \"git stash pop\" or \"git stash drop\" "
 284                          "at any time.\n"));
 285        }
 286
 287        strbuf_release(&autostash);
 288        return 0;
 289}
 290
 291static int finish_rebase(struct rebase_options *opts)
 292{
 293        struct strbuf dir = STRBUF_INIT;
 294        const char *argv_gc_auto[] = { "gc", "--auto", NULL };
 295
 296        delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
 297        apply_autostash(opts);
 298        close_all_packs(the_repository->objects);
 299        /*
 300         * We ignore errors in 'gc --auto', since the
 301         * user should see them.
 302         */
 303        run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
 304        strbuf_addstr(&dir, opts->state_dir);
 305        remove_dir_recursively(&dir, 0);
 306        strbuf_release(&dir);
 307
 308        return 0;
 309}
 310
 311static struct commit *peel_committish(const char *name)
 312{
 313        struct object *obj;
 314        struct object_id oid;
 315
 316        if (get_oid(name, &oid))
 317                return NULL;
 318        obj = parse_object(the_repository, &oid);
 319        return (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
 320}
 321
 322static void add_var(struct strbuf *buf, const char *name, const char *value)
 323{
 324        if (!value)
 325                strbuf_addf(buf, "unset %s; ", name);
 326        else {
 327                strbuf_addf(buf, "%s=", name);
 328                sq_quote_buf(buf, value);
 329                strbuf_addstr(buf, "; ");
 330        }
 331}
 332
 333static const char *resolvemsg =
 334N_("Resolve all conflicts manually, mark them as resolved with\n"
 335"\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
 336"You can instead skip this commit: run \"git rebase --skip\".\n"
 337"To abort and get back to the state before \"git rebase\", run "
 338"\"git rebase --abort\".");
 339
 340static int run_specific_rebase(struct rebase_options *opts)
 341{
 342        const char *argv[] = { NULL, NULL };
 343        struct strbuf script_snippet = STRBUF_INIT;
 344        int status;
 345        const char *backend, *backend_func;
 346
 347        if (opts->type == REBASE_INTERACTIVE) {
 348                /* Run builtin interactive rebase */
 349                struct child_process child = CHILD_PROCESS_INIT;
 350
 351                argv_array_pushf(&child.env_array, "GIT_CHERRY_PICK_HELP=%s",
 352                                 resolvemsg);
 353                if (!(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
 354                        argv_array_push(&child.env_array, "GIT_EDITOR=:");
 355                        opts->autosquash = 0;
 356                }
 357
 358                child.git_cmd = 1;
 359                argv_array_push(&child.args, "rebase--interactive");
 360
 361                if (opts->action)
 362                        argv_array_pushf(&child.args, "--%s", opts->action);
 363                if (opts->keep_empty)
 364                        argv_array_push(&child.args, "--keep-empty");
 365                if (opts->rebase_merges)
 366                        argv_array_push(&child.args, "--rebase-merges");
 367                if (opts->rebase_cousins)
 368                        argv_array_push(&child.args, "--rebase-cousins");
 369                if (opts->autosquash)
 370                        argv_array_push(&child.args, "--autosquash");
 371                if (opts->flags & REBASE_VERBOSE)
 372                        argv_array_push(&child.args, "--verbose");
 373                if (opts->flags & REBASE_FORCE)
 374                        argv_array_push(&child.args, "--no-ff");
 375                if (opts->restrict_revision)
 376                        argv_array_pushf(&child.args,
 377                                         "--restrict-revision=^%s",
 378                                         oid_to_hex(&opts->restrict_revision->object.oid));
 379                if (opts->upstream)
 380                        argv_array_pushf(&child.args, "--upstream=%s",
 381                                         oid_to_hex(&opts->upstream->object.oid));
 382                if (opts->onto)
 383                        argv_array_pushf(&child.args, "--onto=%s",
 384                                         oid_to_hex(&opts->onto->object.oid));
 385                if (opts->squash_onto)
 386                        argv_array_pushf(&child.args, "--squash-onto=%s",
 387                                         oid_to_hex(opts->squash_onto));
 388                if (opts->onto_name)
 389                        argv_array_pushf(&child.args, "--onto-name=%s",
 390                                         opts->onto_name);
 391                argv_array_pushf(&child.args, "--head-name=%s",
 392                                 opts->head_name ?
 393                                 opts->head_name : "detached HEAD");
 394                if (opts->strategy)
 395                        argv_array_pushf(&child.args, "--strategy=%s",
 396                                         opts->strategy);
 397                if (opts->strategy_opts)
 398                        argv_array_pushf(&child.args, "--strategy-opts=%s",
 399                                         opts->strategy_opts);
 400                if (opts->switch_to)
 401                        argv_array_pushf(&child.args, "--switch-to=%s",
 402                                         opts->switch_to);
 403                if (opts->cmd)
 404                        argv_array_pushf(&child.args, "--cmd=%s", opts->cmd);
 405                if (opts->allow_empty_message)
 406                        argv_array_push(&child.args, "--allow-empty-message");
 407                if (opts->allow_rerere_autoupdate > 0)
 408                        argv_array_push(&child.args, "--rerere-autoupdate");
 409                else if (opts->allow_rerere_autoupdate == 0)
 410                        argv_array_push(&child.args, "--no-rerere-autoupdate");
 411                if (opts->gpg_sign_opt)
 412                        argv_array_push(&child.args, opts->gpg_sign_opt);
 413                if (opts->signoff)
 414                        argv_array_push(&child.args, "--signoff");
 415
 416                status = run_command(&child);
 417                goto finished_rebase;
 418        }
 419
 420        add_var(&script_snippet, "GIT_DIR", absolute_path(get_git_dir()));
 421        add_var(&script_snippet, "state_dir", opts->state_dir);
 422
 423        add_var(&script_snippet, "upstream_name", opts->upstream_name);
 424        add_var(&script_snippet, "upstream", opts->upstream ?
 425                oid_to_hex(&opts->upstream->object.oid) : NULL);
 426        add_var(&script_snippet, "head_name",
 427                opts->head_name ? opts->head_name : "detached HEAD");
 428        add_var(&script_snippet, "orig_head", oid_to_hex(&opts->orig_head));
 429        add_var(&script_snippet, "onto", opts->onto ?
 430                oid_to_hex(&opts->onto->object.oid) : NULL);
 431        add_var(&script_snippet, "onto_name", opts->onto_name);
 432        add_var(&script_snippet, "revisions", opts->revisions);
 433        add_var(&script_snippet, "restrict_revision", opts->restrict_revision ?
 434                oid_to_hex(&opts->restrict_revision->object.oid) : NULL);
 435        add_var(&script_snippet, "GIT_QUIET",
 436                opts->flags & REBASE_NO_QUIET ? "" : "t");
 437        add_var(&script_snippet, "git_am_opt", opts->git_am_opt.buf);
 438        add_var(&script_snippet, "verbose",
 439                opts->flags & REBASE_VERBOSE ? "t" : "");
 440        add_var(&script_snippet, "diffstat",
 441                opts->flags & REBASE_DIFFSTAT ? "t" : "");
 442        add_var(&script_snippet, "force_rebase",
 443                opts->flags & REBASE_FORCE ? "t" : "");
 444        if (opts->switch_to)
 445                add_var(&script_snippet, "switch_to", opts->switch_to);
 446        add_var(&script_snippet, "action", opts->action ? opts->action : "");
 447        add_var(&script_snippet, "signoff", opts->signoff ? "--signoff" : "");
 448        add_var(&script_snippet, "allow_rerere_autoupdate",
 449                opts->allow_rerere_autoupdate < 0 ? "" :
 450                opts->allow_rerere_autoupdate ?
 451                "--rerere-autoupdate" : "--no-rerere-autoupdate");
 452        add_var(&script_snippet, "keep_empty", opts->keep_empty ? "yes" : "");
 453        add_var(&script_snippet, "autosquash", opts->autosquash ? "t" : "");
 454        add_var(&script_snippet, "gpg_sign_opt", opts->gpg_sign_opt);
 455        add_var(&script_snippet, "cmd", opts->cmd);
 456        add_var(&script_snippet, "allow_empty_message",
 457                opts->allow_empty_message ?  "--allow-empty-message" : "");
 458        add_var(&script_snippet, "rebase_merges",
 459                opts->rebase_merges ? "t" : "");
 460        add_var(&script_snippet, "rebase_cousins",
 461                opts->rebase_cousins ? "t" : "");
 462        add_var(&script_snippet, "strategy", opts->strategy);
 463        add_var(&script_snippet, "strategy_opts", opts->strategy_opts);
 464        add_var(&script_snippet, "rebase_root", opts->root ? "t" : "");
 465        add_var(&script_snippet, "squash_onto",
 466                opts->squash_onto ? oid_to_hex(opts->squash_onto) : "");
 467        add_var(&script_snippet, "git_format_patch_opt",
 468                opts->git_format_patch_opt.buf);
 469
 470        if (is_interactive(opts) &&
 471            !(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
 472                strbuf_addstr(&script_snippet,
 473                              "GIT_EDITOR=:; export GIT_EDITOR; ");
 474                opts->autosquash = 0;
 475        }
 476
 477        switch (opts->type) {
 478        case REBASE_AM:
 479                backend = "git-rebase--am";
 480                backend_func = "git_rebase__am";
 481                break;
 482        case REBASE_MERGE:
 483                backend = "git-rebase--merge";
 484                backend_func = "git_rebase__merge";
 485                break;
 486        case REBASE_PRESERVE_MERGES:
 487                backend = "git-rebase--preserve-merges";
 488                backend_func = "git_rebase__preserve_merges";
 489                break;
 490        default:
 491                BUG("Unhandled rebase type %d", opts->type);
 492                break;
 493        }
 494
 495        strbuf_addf(&script_snippet,
 496                    ". git-sh-setup && . git-rebase--common &&"
 497                    " . %s && %s", backend, backend_func);
 498        argv[0] = script_snippet.buf;
 499
 500        status = run_command_v_opt(argv, RUN_USING_SHELL);
 501finished_rebase:
 502        if (opts->dont_finish_rebase)
 503                ; /* do nothing */
 504        else if (opts->type == REBASE_INTERACTIVE)
 505                ; /* interactive rebase cleans up after itself */
 506        else if (status == 0) {
 507                if (!file_exists(state_dir_path("stopped-sha", opts)))
 508                        finish_rebase(opts);
 509        } else if (status == 2) {
 510                struct strbuf dir = STRBUF_INIT;
 511
 512                apply_autostash(opts);
 513                strbuf_addstr(&dir, opts->state_dir);
 514                remove_dir_recursively(&dir, 0);
 515                strbuf_release(&dir);
 516                die("Nothing to do");
 517        }
 518
 519        strbuf_release(&script_snippet);
 520
 521        return status ? -1 : 0;
 522}
 523
 524#define GIT_REFLOG_ACTION_ENVIRONMENT "GIT_REFLOG_ACTION"
 525
 526static int reset_head(struct object_id *oid, const char *action,
 527                      const char *switch_to_branch, int detach_head,
 528                      const char *reflog_orig_head, const char *reflog_head)
 529{
 530        struct object_id head_oid;
 531        struct tree_desc desc;
 532        struct lock_file lock = LOCK_INIT;
 533        struct unpack_trees_options unpack_tree_opts;
 534        struct tree *tree;
 535        const char *reflog_action;
 536        struct strbuf msg = STRBUF_INIT;
 537        size_t prefix_len;
 538        struct object_id *orig = NULL, oid_orig,
 539                *old_orig = NULL, oid_old_orig;
 540        int ret = 0;
 541
 542        if (switch_to_branch && !starts_with(switch_to_branch, "refs/"))
 543                BUG("Not a fully qualified branch: '%s'", switch_to_branch);
 544
 545        if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
 546                return -1;
 547
 548        if (!oid) {
 549                if (get_oid("HEAD", &head_oid)) {
 550                        rollback_lock_file(&lock);
 551                        return error(_("could not determine HEAD revision"));
 552                }
 553                oid = &head_oid;
 554        }
 555
 556        memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
 557        setup_unpack_trees_porcelain(&unpack_tree_opts, action);
 558        unpack_tree_opts.head_idx = 1;
 559        unpack_tree_opts.src_index = the_repository->index;
 560        unpack_tree_opts.dst_index = the_repository->index;
 561        unpack_tree_opts.fn = oneway_merge;
 562        unpack_tree_opts.update = 1;
 563        unpack_tree_opts.merge = 1;
 564        if (!detach_head)
 565                unpack_tree_opts.reset = 1;
 566
 567        if (read_index_unmerged(the_repository->index) < 0) {
 568                rollback_lock_file(&lock);
 569                return error(_("could not read index"));
 570        }
 571
 572        if (!fill_tree_descriptor(&desc, oid)) {
 573                error(_("failed to find tree of %s"), oid_to_hex(oid));
 574                rollback_lock_file(&lock);
 575                free((void *)desc.buffer);
 576                return -1;
 577        }
 578
 579        if (unpack_trees(1, &desc, &unpack_tree_opts)) {
 580                rollback_lock_file(&lock);
 581                free((void *)desc.buffer);
 582                return -1;
 583        }
 584
 585        tree = parse_tree_indirect(oid);
 586        prime_cache_tree(the_repository->index, tree);
 587
 588        if (write_locked_index(the_repository->index, &lock, COMMIT_LOCK) < 0)
 589                ret = error(_("could not write index"));
 590        free((void *)desc.buffer);
 591
 592        if (ret)
 593                return ret;
 594
 595        reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
 596        strbuf_addf(&msg, "%s: ", reflog_action ? reflog_action : "rebase");
 597        prefix_len = msg.len;
 598
 599        if (!get_oid("ORIG_HEAD", &oid_old_orig))
 600                old_orig = &oid_old_orig;
 601        if (!get_oid("HEAD", &oid_orig)) {
 602                orig = &oid_orig;
 603                if (!reflog_orig_head) {
 604                        strbuf_addstr(&msg, "updating ORIG_HEAD");
 605                        reflog_orig_head = msg.buf;
 606                }
 607                update_ref(reflog_orig_head, "ORIG_HEAD", orig, old_orig, 0,
 608                           UPDATE_REFS_MSG_ON_ERR);
 609        } else if (old_orig)
 610                delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
 611        if (!reflog_head) {
 612                strbuf_setlen(&msg, prefix_len);
 613                strbuf_addstr(&msg, "updating HEAD");
 614                reflog_head = msg.buf;
 615        }
 616        if (!switch_to_branch)
 617                ret = update_ref(reflog_head, "HEAD", oid, orig, REF_NO_DEREF,
 618                                 UPDATE_REFS_MSG_ON_ERR);
 619        else {
 620                ret = create_symref("HEAD", switch_to_branch, msg.buf);
 621                if (!ret)
 622                        ret = update_ref(reflog_head, "HEAD", oid, NULL, 0,
 623                                         UPDATE_REFS_MSG_ON_ERR);
 624        }
 625
 626        strbuf_release(&msg);
 627        return ret;
 628}
 629
 630static int rebase_config(const char *var, const char *value, void *data)
 631{
 632        struct rebase_options *opts = data;
 633
 634        if (!strcmp(var, "rebase.stat")) {
 635                if (git_config_bool(var, value))
 636                        opts->flags |= REBASE_DIFFSTAT;
 637                else
 638                        opts->flags &= !REBASE_DIFFSTAT;
 639                return 0;
 640        }
 641
 642        if (!strcmp(var, "rebase.autosquash")) {
 643                opts->autosquash = git_config_bool(var, value);
 644                return 0;
 645        }
 646
 647        if (!strcmp(var, "commit.gpgsign")) {
 648                free(opts->gpg_sign_opt);
 649                opts->gpg_sign_opt = git_config_bool(var, value) ?
 650                        xstrdup("-S") : NULL;
 651                return 0;
 652        }
 653
 654        if (!strcmp(var, "rebase.autostash")) {
 655                opts->autostash = git_config_bool(var, value);
 656                return 0;
 657        }
 658
 659        return git_default_config(var, value, data);
 660}
 661
 662/*
 663 * Determines whether the commits in from..to are linear, i.e. contain
 664 * no merge commits. This function *expects* `from` to be an ancestor of
 665 * `to`.
 666 */
 667static int is_linear_history(struct commit *from, struct commit *to)
 668{
 669        while (to && to != from) {
 670                parse_commit(to);
 671                if (!to->parents)
 672                        return 1;
 673                if (to->parents->next)
 674                        return 0;
 675                to = to->parents->item;
 676        }
 677        return 1;
 678}
 679
 680static int can_fast_forward(struct commit *onto, struct object_id *head_oid,
 681                            struct object_id *merge_base)
 682{
 683        struct commit *head = lookup_commit(the_repository, head_oid);
 684        struct commit_list *merge_bases;
 685        int res;
 686
 687        if (!head)
 688                return 0;
 689
 690        merge_bases = get_merge_bases(onto, head);
 691        if (merge_bases && !merge_bases->next) {
 692                oidcpy(merge_base, &merge_bases->item->object.oid);
 693                res = oideq(merge_base, &onto->object.oid);
 694        } else {
 695                oidcpy(merge_base, &null_oid);
 696                res = 0;
 697        }
 698        free_commit_list(merge_bases);
 699        return res && is_linear_history(onto, head);
 700}
 701
 702/* -i followed by -m is still -i */
 703static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
 704{
 705        struct rebase_options *opts = opt->value;
 706
 707        if (!is_interactive(opts))
 708                opts->type = REBASE_MERGE;
 709
 710        return 0;
 711}
 712
 713/* -i followed by -p is still explicitly interactive, but -p alone is not */
 714static int parse_opt_interactive(const struct option *opt, const char *arg,
 715                                 int unset)
 716{
 717        struct rebase_options *opts = opt->value;
 718
 719        opts->type = REBASE_INTERACTIVE;
 720        opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
 721
 722        return 0;
 723}
 724
 725static void NORETURN error_on_missing_default_upstream(void)
 726{
 727        struct branch *current_branch = branch_get(NULL);
 728
 729        printf(_("%s\n"
 730                 "Please specify which branch you want to rebase against.\n"
 731                 "See git-rebase(1) for details.\n"
 732                 "\n"
 733                 "    git rebase '<branch>'\n"
 734                 "\n"),
 735                current_branch ? _("There is no tracking information for "
 736                        "the current branch.") :
 737                        _("You are not currently on a branch."));
 738
 739        if (current_branch) {
 740                const char *remote = current_branch->remote_name;
 741
 742                if (!remote)
 743                        remote = _("<remote>");
 744
 745                printf(_("If you wish to set tracking information for this "
 746                         "branch you can do so with:\n"
 747                         "\n"
 748                         "    git branch --set-upstream-to=%s/<branch> %s\n"
 749                         "\n"),
 750                       remote, current_branch->name);
 751        }
 752        exit(1);
 753}
 754
 755int cmd_rebase(int argc, const char **argv, const char *prefix)
 756{
 757        struct rebase_options options = {
 758                .type = REBASE_UNSPECIFIED,
 759                .flags = REBASE_NO_QUIET,
 760                .git_am_opt = STRBUF_INIT,
 761                .allow_rerere_autoupdate  = -1,
 762                .allow_empty_message = 1,
 763                .git_format_patch_opt = STRBUF_INIT,
 764        };
 765        const char *branch_name;
 766        int ret, flags, total_argc, in_progress = 0;
 767        int ok_to_skip_pre_rebase = 0;
 768        struct strbuf msg = STRBUF_INIT;
 769        struct strbuf revisions = STRBUF_INIT;
 770        struct strbuf buf = STRBUF_INIT;
 771        struct object_id merge_base;
 772        enum {
 773                NO_ACTION,
 774                ACTION_CONTINUE,
 775                ACTION_SKIP,
 776                ACTION_ABORT,
 777                ACTION_QUIT,
 778                ACTION_EDIT_TODO,
 779                ACTION_SHOW_CURRENT_PATCH,
 780        } action = NO_ACTION;
 781        int committer_date_is_author_date = 0;
 782        int ignore_date = 0;
 783        int ignore_whitespace = 0;
 784        const char *gpg_sign = NULL;
 785        int opt_c = -1;
 786        struct string_list whitespace = STRING_LIST_INIT_NODUP;
 787        struct string_list exec = STRING_LIST_INIT_NODUP;
 788        const char *rebase_merges = NULL;
 789        int fork_point = -1;
 790        struct string_list strategy_options = STRING_LIST_INIT_NODUP;
 791        struct object_id squash_onto;
 792        char *squash_onto_name = NULL;
 793        struct option builtin_rebase_options[] = {
 794                OPT_STRING(0, "onto", &options.onto_name,
 795                           N_("revision"),
 796                           N_("rebase onto given branch instead of upstream")),
 797                OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
 798                         N_("allow pre-rebase hook to run")),
 799                OPT_NEGBIT('q', "quiet", &options.flags,
 800                           N_("be quiet. implies --no-stat"),
 801                           REBASE_NO_QUIET| REBASE_VERBOSE | REBASE_DIFFSTAT),
 802                OPT_BIT('v', "verbose", &options.flags,
 803                        N_("display a diffstat of what changed upstream"),
 804                        REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
 805                {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
 806                        N_("do not show diffstat of what changed upstream"),
 807                        PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
 808                OPT_BOOL(0, "ignore-whitespace", &ignore_whitespace,
 809                         N_("passed to 'git apply'")),
 810                OPT_BOOL(0, "signoff", &options.signoff,
 811                         N_("add a Signed-off-by: line to each commit")),
 812                OPT_BOOL(0, "committer-date-is-author-date",
 813                         &committer_date_is_author_date,
 814                         N_("passed to 'git am'")),
 815                OPT_BOOL(0, "ignore-date", &ignore_date,
 816                         N_("passed to 'git am'")),
 817                OPT_BIT('f', "force-rebase", &options.flags,
 818                        N_("cherry-pick all commits, even if unchanged"),
 819                        REBASE_FORCE),
 820                OPT_BIT(0, "no-ff", &options.flags,
 821                        N_("cherry-pick all commits, even if unchanged"),
 822                        REBASE_FORCE),
 823                OPT_CMDMODE(0, "continue", &action, N_("continue"),
 824                            ACTION_CONTINUE),
 825                OPT_CMDMODE(0, "skip", &action,
 826                            N_("skip current patch and continue"), ACTION_SKIP),
 827                OPT_CMDMODE(0, "abort", &action,
 828                            N_("abort and check out the original branch"),
 829                            ACTION_ABORT),
 830                OPT_CMDMODE(0, "quit", &action,
 831                            N_("abort but keep HEAD where it is"), ACTION_QUIT),
 832                OPT_CMDMODE(0, "edit-todo", &action, N_("edit the todo list "
 833                            "during an interactive rebase"), ACTION_EDIT_TODO),
 834                OPT_CMDMODE(0, "show-current-patch", &action,
 835                            N_("show the patch file being applied or merged"),
 836                            ACTION_SHOW_CURRENT_PATCH),
 837                { OPTION_CALLBACK, 'm', "merge", &options, NULL,
 838                        N_("use merging strategies to rebase"),
 839                        PARSE_OPT_NOARG | PARSE_OPT_NONEG,
 840                        parse_opt_merge },
 841                { OPTION_CALLBACK, 'i', "interactive", &options, NULL,
 842                        N_("let the user edit the list of commits to rebase"),
 843                        PARSE_OPT_NOARG | PARSE_OPT_NONEG,
 844                        parse_opt_interactive },
 845                OPT_SET_INT('p', "preserve-merges", &options.type,
 846                            N_("try to recreate merges instead of ignoring "
 847                               "them"), REBASE_PRESERVE_MERGES),
 848                OPT_BOOL(0, "rerere-autoupdate",
 849                         &options.allow_rerere_autoupdate,
 850                         N_("allow rerere to update index  with resolved "
 851                            "conflict")),
 852                OPT_BOOL('k', "keep-empty", &options.keep_empty,
 853                         N_("preserve empty commits during rebase")),
 854                OPT_BOOL(0, "autosquash", &options.autosquash,
 855                         N_("move commits that begin with "
 856                            "squash!/fixup! under -i")),
 857                { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
 858                        N_("GPG-sign commits"),
 859                        PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
 860                OPT_STRING_LIST(0, "whitespace", &whitespace,
 861                                N_("whitespace"), N_("passed to 'git apply'")),
 862                OPT_SET_INT('C', NULL, &opt_c, N_("passed to 'git apply'"),
 863                            REBASE_AM),
 864                OPT_BOOL(0, "autostash", &options.autostash,
 865                         N_("automatically stash/stash pop before and after")),
 866                OPT_STRING_LIST('x', "exec", &exec, N_("exec"),
 867                                N_("add exec lines after each commit of the "
 868                                   "editable list")),
 869                OPT_BOOL(0, "allow-empty-message",
 870                         &options.allow_empty_message,
 871                         N_("allow rebasing commits with empty messages")),
 872                {OPTION_STRING, 'r', "rebase-merges", &rebase_merges,
 873                        N_("mode"),
 874                        N_("try to rebase merges instead of skipping them"),
 875                        PARSE_OPT_OPTARG, NULL, (intptr_t)""},
 876                OPT_BOOL(0, "fork-point", &fork_point,
 877                         N_("use 'merge-base --fork-point' to refine upstream")),
 878                OPT_STRING('s', "strategy", &options.strategy,
 879                           N_("strategy"), N_("use the given merge strategy")),
 880                OPT_STRING_LIST('X', "strategy-option", &strategy_options,
 881                                N_("option"),
 882                                N_("pass the argument through to the merge "
 883                                   "strategy")),
 884                OPT_BOOL(0, "root", &options.root,
 885                         N_("rebase all reachable commits up to the root(s)")),
 886                OPT_END(),
 887        };
 888
 889        /*
 890         * NEEDSWORK: Once the builtin rebase has been tested enough
 891         * and git-legacy-rebase.sh is retired to contrib/, this preamble
 892         * can be removed.
 893         */
 894
 895        if (!use_builtin_rebase()) {
 896                const char *path = mkpath("%s/git-legacy-rebase",
 897                                          git_exec_path());
 898
 899                if (sane_execvp(path, (char **)argv) < 0)
 900                        die_errno(_("could not exec %s"), path);
 901                else
 902                        BUG("sane_execvp() returned???");
 903        }
 904
 905        if (argc == 2 && !strcmp(argv[1], "-h"))
 906                usage_with_options(builtin_rebase_usage,
 907                                   builtin_rebase_options);
 908
 909        prefix = setup_git_directory();
 910        trace_repo_setup(prefix);
 911        setup_work_tree();
 912
 913        git_config(rebase_config, &options);
 914
 915        strbuf_reset(&buf);
 916        strbuf_addf(&buf, "%s/applying", apply_dir());
 917        if(file_exists(buf.buf))
 918                die(_("It looks like 'git am' is in progress. Cannot rebase."));
 919
 920        if (is_directory(apply_dir())) {
 921                options.type = REBASE_AM;
 922                options.state_dir = apply_dir();
 923        } else if (is_directory(merge_dir())) {
 924                strbuf_reset(&buf);
 925                strbuf_addf(&buf, "%s/rewritten", merge_dir());
 926                if (is_directory(buf.buf)) {
 927                        options.type = REBASE_PRESERVE_MERGES;
 928                        options.flags |= REBASE_INTERACTIVE_EXPLICIT;
 929                } else {
 930                        strbuf_reset(&buf);
 931                        strbuf_addf(&buf, "%s/interactive", merge_dir());
 932                        if(file_exists(buf.buf)) {
 933                                options.type = REBASE_INTERACTIVE;
 934                                options.flags |= REBASE_INTERACTIVE_EXPLICIT;
 935                        } else
 936                                options.type = REBASE_MERGE;
 937                }
 938                options.state_dir = merge_dir();
 939        }
 940
 941        if (options.type != REBASE_UNSPECIFIED)
 942                in_progress = 1;
 943
 944        total_argc = argc;
 945        argc = parse_options(argc, argv, prefix,
 946                             builtin_rebase_options,
 947                             builtin_rebase_usage, 0);
 948
 949        if (action != NO_ACTION && total_argc != 2) {
 950                usage_with_options(builtin_rebase_usage,
 951                                   builtin_rebase_options);
 952        }
 953
 954        if (argc > 2)
 955                usage_with_options(builtin_rebase_usage,
 956                                   builtin_rebase_options);
 957
 958        if (action != NO_ACTION && !in_progress)
 959                die(_("No rebase in progress?"));
 960
 961        if (action == ACTION_EDIT_TODO && !is_interactive(&options))
 962                die(_("The --edit-todo action can only be used during "
 963                      "interactive rebase."));
 964
 965        switch (action) {
 966        case ACTION_CONTINUE: {
 967                struct object_id head;
 968                struct lock_file lock_file = LOCK_INIT;
 969                int fd;
 970
 971                options.action = "continue";
 972
 973                /* Sanity check */
 974                if (get_oid("HEAD", &head))
 975                        die(_("Cannot read HEAD"));
 976
 977                fd = hold_locked_index(&lock_file, 0);
 978                if (read_index(the_repository->index) < 0)
 979                        die(_("could not read index"));
 980                refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
 981                              NULL);
 982                if (0 <= fd)
 983                        update_index_if_able(the_repository->index,
 984                                             &lock_file);
 985                rollback_lock_file(&lock_file);
 986
 987                if (has_unstaged_changes(1)) {
 988                        puts(_("You must edit all merge conflicts and then\n"
 989                               "mark them as resolved using git add"));
 990                        exit(1);
 991                }
 992                if (read_basic_state(&options))
 993                        exit(1);
 994                goto run_rebase;
 995        }
 996        case ACTION_SKIP: {
 997                struct string_list merge_rr = STRING_LIST_INIT_DUP;
 998
 999                options.action = "skip";
1000
1001                rerere_clear(&merge_rr);
1002                string_list_clear(&merge_rr, 1);
1003
1004                if (reset_head(NULL, "reset", NULL, 0, NULL, NULL) < 0)
1005                        die(_("could not discard worktree changes"));
1006                remove_branch_state();
1007                if (read_basic_state(&options))
1008                        exit(1);
1009                goto run_rebase;
1010        }
1011        case ACTION_ABORT: {
1012                struct string_list merge_rr = STRING_LIST_INIT_DUP;
1013                options.action = "abort";
1014
1015                rerere_clear(&merge_rr);
1016                string_list_clear(&merge_rr, 1);
1017
1018                if (read_basic_state(&options))
1019                        exit(1);
1020                if (reset_head(&options.orig_head, "reset",
1021                               options.head_name, 0, NULL, NULL) < 0)
1022                        die(_("could not move back to %s"),
1023                            oid_to_hex(&options.orig_head));
1024                remove_branch_state();
1025                ret = finish_rebase(&options);
1026                goto cleanup;
1027        }
1028        case ACTION_QUIT: {
1029                strbuf_reset(&buf);
1030                strbuf_addstr(&buf, options.state_dir);
1031                ret = !!remove_dir_recursively(&buf, 0);
1032                if (ret)
1033                        die(_("could not remove '%s'"), options.state_dir);
1034                goto cleanup;
1035        }
1036        case ACTION_EDIT_TODO:
1037                options.action = "edit-todo";
1038                options.dont_finish_rebase = 1;
1039                goto run_rebase;
1040        case ACTION_SHOW_CURRENT_PATCH:
1041                options.action = "show-current-patch";
1042                options.dont_finish_rebase = 1;
1043                goto run_rebase;
1044        case NO_ACTION:
1045                break;
1046        default:
1047                BUG("action: %d", action);
1048        }
1049
1050        /* Make sure no rebase is in progress */
1051        if (in_progress) {
1052                const char *last_slash = strrchr(options.state_dir, '/');
1053                const char *state_dir_base =
1054                        last_slash ? last_slash + 1 : options.state_dir;
1055                const char *cmd_live_rebase =
1056                        "git rebase (--continue | --abort | --skip)";
1057                strbuf_reset(&buf);
1058                strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
1059                die(_("It seems that there is already a %s directory, and\n"
1060                      "I wonder if you are in the middle of another rebase.  "
1061                      "If that is the\n"
1062                      "case, please try\n\t%s\n"
1063                      "If that is not the case, please\n\t%s\n"
1064                      "and run me again.  I am stopping in case you still "
1065                      "have something\n"
1066                      "valuable there.\n"),
1067                    state_dir_base, cmd_live_rebase, buf.buf);
1068        }
1069
1070        if (!(options.flags & REBASE_NO_QUIET))
1071                strbuf_addstr(&options.git_am_opt, " -q");
1072
1073        if (committer_date_is_author_date) {
1074                strbuf_addstr(&options.git_am_opt,
1075                              " --committer-date-is-author-date");
1076                options.flags |= REBASE_FORCE;
1077        }
1078
1079        if (ignore_whitespace)
1080                strbuf_addstr(&options.git_am_opt, " --ignore-whitespace");
1081
1082        if (ignore_date) {
1083                strbuf_addstr(&options.git_am_opt, " --ignore-date");
1084                options.flags |= REBASE_FORCE;
1085        }
1086
1087        if (options.keep_empty)
1088                imply_interactive(&options, "--keep-empty");
1089
1090        if (gpg_sign) {
1091                free(options.gpg_sign_opt);
1092                options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
1093        }
1094
1095        if (opt_c >= 0)
1096                strbuf_addf(&options.git_am_opt, " -C%d", opt_c);
1097
1098        if (whitespace.nr) {
1099                int i;
1100
1101                for (i = 0; i < whitespace.nr; i++) {
1102                        const char *item = whitespace.items[i].string;
1103
1104                        strbuf_addf(&options.git_am_opt, " --whitespace=%s",
1105                                    item);
1106
1107                        if ((!strcmp(item, "fix")) || (!strcmp(item, "strip")))
1108                                options.flags |= REBASE_FORCE;
1109                }
1110        }
1111
1112        if (exec.nr) {
1113                int i;
1114
1115                imply_interactive(&options, "--exec");
1116
1117                strbuf_reset(&buf);
1118                for (i = 0; i < exec.nr; i++)
1119                        strbuf_addf(&buf, "exec %s\n", exec.items[i].string);
1120                options.cmd = xstrdup(buf.buf);
1121        }
1122
1123        if (rebase_merges) {
1124                if (!*rebase_merges)
1125                        ; /* default mode; do nothing */
1126                else if (!strcmp("rebase-cousins", rebase_merges))
1127                        options.rebase_cousins = 1;
1128                else if (strcmp("no-rebase-cousins", rebase_merges))
1129                        die(_("Unknown mode: %s"), rebase_merges);
1130                options.rebase_merges = 1;
1131                imply_interactive(&options, "--rebase-merges");
1132        }
1133
1134        if (strategy_options.nr) {
1135                int i;
1136
1137                if (!options.strategy)
1138                        options.strategy = "recursive";
1139
1140                strbuf_reset(&buf);
1141                for (i = 0; i < strategy_options.nr; i++)
1142                        strbuf_addf(&buf, " --%s",
1143                                    strategy_options.items[i].string);
1144                options.strategy_opts = xstrdup(buf.buf);
1145        }
1146
1147        if (options.strategy) {
1148                options.strategy = xstrdup(options.strategy);
1149                switch (options.type) {
1150                case REBASE_AM:
1151                        die(_("--strategy requires --merge or --interactive"));
1152                case REBASE_MERGE:
1153                case REBASE_INTERACTIVE:
1154                case REBASE_PRESERVE_MERGES:
1155                        /* compatible */
1156                        break;
1157                case REBASE_UNSPECIFIED:
1158                        options.type = REBASE_MERGE;
1159                        break;
1160                default:
1161                        BUG("unhandled rebase type (%d)", options.type);
1162                }
1163        }
1164
1165        if (options.root && !options.onto_name)
1166                imply_interactive(&options, "--root without --onto");
1167
1168        if (isatty(2) && options.flags & REBASE_NO_QUIET)
1169                strbuf_addstr(&options.git_format_patch_opt, " --progress");
1170
1171        switch (options.type) {
1172        case REBASE_MERGE:
1173        case REBASE_INTERACTIVE:
1174        case REBASE_PRESERVE_MERGES:
1175                options.state_dir = merge_dir();
1176                break;
1177        case REBASE_AM:
1178                options.state_dir = apply_dir();
1179                break;
1180        default:
1181                /* the default rebase backend is `--am` */
1182                options.type = REBASE_AM;
1183                options.state_dir = apply_dir();
1184                break;
1185        }
1186
1187        if (options.git_am_opt.len) {
1188                const char *p;
1189
1190                /* all am options except -q are compatible only with --am */
1191                strbuf_reset(&buf);
1192                strbuf_addbuf(&buf, &options.git_am_opt);
1193                strbuf_addch(&buf, ' ');
1194                while ((p = strstr(buf.buf, " -q ")))
1195                        strbuf_splice(&buf, p - buf.buf, 4, " ", 1);
1196                strbuf_trim(&buf);
1197
1198                if (is_interactive(&options) && buf.len)
1199                        die(_("error: cannot combine interactive options "
1200                              "(--interactive, --exec, --rebase-merges, "
1201                              "--preserve-merges, --keep-empty, --root + "
1202                              "--onto) with am options (%s)"), buf.buf);
1203                if (options.type == REBASE_MERGE && buf.len)
1204                        die(_("error: cannot combine merge options (--merge, "
1205                              "--strategy, --strategy-option) with am options "
1206                              "(%s)"), buf.buf);
1207        }
1208
1209        if (options.signoff) {
1210                if (options.type == REBASE_PRESERVE_MERGES)
1211                        die("cannot combine '--signoff' with "
1212                            "'--preserve-merges'");
1213                strbuf_addstr(&options.git_am_opt, " --signoff");
1214                options.flags |= REBASE_FORCE;
1215        }
1216
1217        if (options.type == REBASE_PRESERVE_MERGES)
1218                /*
1219                 * Note: incompatibility with --signoff handled in signoff block above
1220                 * Note: incompatibility with --interactive is just a strong warning;
1221                 *       git-rebase.txt caveats with "unless you know what you are doing"
1222                 */
1223                if (options.rebase_merges)
1224                        die(_("error: cannot combine '--preserve-merges' with "
1225                              "'--rebase-merges'"));
1226
1227        if (options.rebase_merges) {
1228                if (strategy_options.nr)
1229                        die(_("error: cannot combine '--rebase-merges' with "
1230                              "'--strategy-option'"));
1231                if (options.strategy)
1232                        die(_("error: cannot combine '--rebase-merges' with "
1233                              "'--strategy'"));
1234        }
1235
1236        if (!options.root) {
1237                if (argc < 1) {
1238                        struct branch *branch;
1239
1240                        branch = branch_get(NULL);
1241                        options.upstream_name = branch_get_upstream(branch,
1242                                                                    NULL);
1243                        if (!options.upstream_name)
1244                                error_on_missing_default_upstream();
1245                        if (fork_point < 0)
1246                                fork_point = 1;
1247                } else {
1248                        options.upstream_name = argv[0];
1249                        argc--;
1250                        argv++;
1251                        if (!strcmp(options.upstream_name, "-"))
1252                                options.upstream_name = "@{-1}";
1253                }
1254                options.upstream = peel_committish(options.upstream_name);
1255                if (!options.upstream)
1256                        die(_("invalid upstream '%s'"), options.upstream_name);
1257                options.upstream_arg = options.upstream_name;
1258        } else {
1259                if (!options.onto_name) {
1260                        if (commit_tree("", 0, the_hash_algo->empty_tree, NULL,
1261                                        &squash_onto, NULL, NULL) < 0)
1262                                die(_("Could not create new root commit"));
1263                        options.squash_onto = &squash_onto;
1264                        options.onto_name = squash_onto_name =
1265                                xstrdup(oid_to_hex(&squash_onto));
1266                }
1267                options.upstream_name = NULL;
1268                options.upstream = NULL;
1269                if (argc > 1)
1270                        usage_with_options(builtin_rebase_usage,
1271                                           builtin_rebase_options);
1272                options.upstream_arg = "--root";
1273        }
1274
1275        /* Make sure the branch to rebase onto is valid. */
1276        if (!options.onto_name)
1277                options.onto_name = options.upstream_name;
1278        if (strstr(options.onto_name, "...")) {
1279                if (get_oid_mb(options.onto_name, &merge_base) < 0)
1280                        die(_("'%s': need exactly one merge base"),
1281                            options.onto_name);
1282                options.onto = lookup_commit_or_die(&merge_base,
1283                                                    options.onto_name);
1284        } else {
1285                options.onto = peel_committish(options.onto_name);
1286                if (!options.onto)
1287                        die(_("Does not point to a valid commit '%s'"),
1288                                options.onto_name);
1289        }
1290
1291        /*
1292         * If the branch to rebase is given, that is the branch we will rebase
1293         * branch_name -- branch/commit being rebased, or
1294         *                HEAD (already detached)
1295         * orig_head -- commit object name of tip of the branch before rebasing
1296         * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
1297         */
1298        if (argc == 1) {
1299                /* Is it "rebase other branchname" or "rebase other commit"? */
1300                branch_name = argv[0];
1301                options.switch_to = argv[0];
1302
1303                /* Is it a local branch? */
1304                strbuf_reset(&buf);
1305                strbuf_addf(&buf, "refs/heads/%s", branch_name);
1306                if (!read_ref(buf.buf, &options.orig_head))
1307                        options.head_name = xstrdup(buf.buf);
1308                /* If not is it a valid ref (branch or commit)? */
1309                else if (!get_oid(branch_name, &options.orig_head))
1310                        options.head_name = NULL;
1311                else
1312                        die(_("fatal: no such branch/commit '%s'"),
1313                            branch_name);
1314        } else if (argc == 0) {
1315                /* Do not need to switch branches, we are already on it. */
1316                options.head_name =
1317                        xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
1318                                         &flags));
1319                if (!options.head_name)
1320                        die(_("No such ref: %s"), "HEAD");
1321                if (flags & REF_ISSYMREF) {
1322                        if (!skip_prefix(options.head_name,
1323                                         "refs/heads/", &branch_name))
1324                                branch_name = options.head_name;
1325
1326                } else {
1327                        free(options.head_name);
1328                        options.head_name = NULL;
1329                        branch_name = "HEAD";
1330                }
1331                if (get_oid("HEAD", &options.orig_head))
1332                        die(_("Could not resolve HEAD to a revision"));
1333        } else
1334                BUG("unexpected number of arguments left to parse");
1335
1336        if (fork_point > 0) {
1337                struct commit *head =
1338                        lookup_commit_reference(the_repository,
1339                                                &options.orig_head);
1340                options.restrict_revision =
1341                        get_fork_point(options.upstream_name, head);
1342        }
1343
1344        if (read_index(the_repository->index) < 0)
1345                die(_("could not read index"));
1346
1347        if (options.autostash) {
1348                struct lock_file lock_file = LOCK_INIT;
1349                int fd;
1350
1351                fd = hold_locked_index(&lock_file, 0);
1352                refresh_cache(REFRESH_QUIET);
1353                if (0 <= fd)
1354                        update_index_if_able(&the_index, &lock_file);
1355                rollback_lock_file(&lock_file);
1356
1357                if (has_unstaged_changes(1) || has_uncommitted_changes(1)) {
1358                        const char *autostash =
1359                                state_dir_path("autostash", &options);
1360                        struct child_process stash = CHILD_PROCESS_INIT;
1361                        struct object_id oid;
1362                        struct commit *head =
1363                                lookup_commit_reference(the_repository,
1364                                                        &options.orig_head);
1365
1366                        argv_array_pushl(&stash.args,
1367                                         "stash", "create", "autostash", NULL);
1368                        stash.git_cmd = 1;
1369                        stash.no_stdin = 1;
1370                        strbuf_reset(&buf);
1371                        if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
1372                                die(_("Cannot autostash"));
1373                        strbuf_trim_trailing_newline(&buf);
1374                        if (get_oid(buf.buf, &oid))
1375                                die(_("Unexpected stash response: '%s'"),
1376                                    buf.buf);
1377                        strbuf_reset(&buf);
1378                        strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
1379
1380                        if (safe_create_leading_directories_const(autostash))
1381                                die(_("Could not create directory for '%s'"),
1382                                    options.state_dir);
1383                        write_file(autostash, "%s", oid_to_hex(&oid));
1384                        printf(_("Created autostash: %s\n"), buf.buf);
1385                        if (reset_head(&head->object.oid, "reset --hard",
1386                                       NULL, 0, NULL, NULL) < 0)
1387                                die(_("could not reset --hard"));
1388                        printf(_("HEAD is now at %s"),
1389                               find_unique_abbrev(&head->object.oid,
1390                                                  DEFAULT_ABBREV));
1391                        strbuf_reset(&buf);
1392                        pp_commit_easy(CMIT_FMT_ONELINE, head, &buf);
1393                        if (buf.len > 0)
1394                                printf(" %s", buf.buf);
1395                        putchar('\n');
1396
1397                        if (discard_index(the_repository->index) < 0 ||
1398                                read_index(the_repository->index) < 0)
1399                                die(_("could not read index"));
1400                }
1401        }
1402
1403        if (require_clean_work_tree("rebase",
1404                                    _("Please commit or stash them."), 1, 1)) {
1405                ret = 1;
1406                goto cleanup;
1407        }
1408
1409        /*
1410         * Now we are rebasing commits upstream..orig_head (or with --root,
1411         * everything leading up to orig_head) on top of onto.
1412         */
1413
1414        /*
1415         * Check if we are already based on onto with linear history,
1416         * but this should be done only when upstream and onto are the same
1417         * and if this is not an interactive rebase.
1418         */
1419        if (can_fast_forward(options.onto, &options.orig_head, &merge_base) &&
1420            !is_interactive(&options) && !options.restrict_revision &&
1421            options.upstream &&
1422            !oidcmp(&options.upstream->object.oid, &options.onto->object.oid)) {
1423                int flag;
1424
1425                if (!(options.flags & REBASE_FORCE)) {
1426                        /* Lazily switch to the target branch if needed... */
1427                        if (options.switch_to) {
1428                                struct object_id oid;
1429
1430                                if (get_oid(options.switch_to, &oid) < 0) {
1431                                        ret = !!error(_("could not parse '%s'"),
1432                                                      options.switch_to);
1433                                        goto cleanup;
1434                                }
1435
1436                                strbuf_reset(&buf);
1437                                strbuf_addf(&buf, "rebase: checkout %s",
1438                                            options.switch_to);
1439                                if (reset_head(&oid, "checkout",
1440                                               options.head_name, 0,
1441                                               NULL, NULL) < 0) {
1442                                        ret = !!error(_("could not switch to "
1443                                                        "%s"),
1444                                                      options.switch_to);
1445                                        goto cleanup;
1446                                }
1447                        }
1448
1449                        if (!(options.flags & REBASE_NO_QUIET))
1450                                ; /* be quiet */
1451                        else if (!strcmp(branch_name, "HEAD") &&
1452                                 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1453                                puts(_("HEAD is up to date."));
1454                        else
1455                                printf(_("Current branch %s is up to date.\n"),
1456                                       branch_name);
1457                        ret = !!finish_rebase(&options);
1458                        goto cleanup;
1459                } else if (!(options.flags & REBASE_NO_QUIET))
1460                        ; /* be quiet */
1461                else if (!strcmp(branch_name, "HEAD") &&
1462                         resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1463                        puts(_("HEAD is up to date, rebase forced."));
1464                else
1465                        printf(_("Current branch %s is up to date, rebase "
1466                                 "forced.\n"), branch_name);
1467        }
1468
1469        /* If a hook exists, give it a chance to interrupt*/
1470        if (!ok_to_skip_pre_rebase &&
1471            run_hook_le(NULL, "pre-rebase", options.upstream_arg,
1472                        argc ? argv[0] : NULL, NULL))
1473                die(_("The pre-rebase hook refused to rebase."));
1474
1475        if (options.flags & REBASE_DIFFSTAT) {
1476                struct diff_options opts;
1477
1478                if (options.flags & REBASE_VERBOSE)
1479                        printf(_("Changes from %s to %s:\n"),
1480                                oid_to_hex(&merge_base),
1481                                oid_to_hex(&options.onto->object.oid));
1482
1483                /* We want color (if set), but no pager */
1484                diff_setup(&opts);
1485                opts.stat_width = -1; /* use full terminal width */
1486                opts.stat_graph_width = -1; /* respect statGraphWidth config */
1487                opts.output_format |=
1488                        DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1489                opts.detect_rename = DIFF_DETECT_RENAME;
1490                diff_setup_done(&opts);
1491                diff_tree_oid(&merge_base, &options.onto->object.oid,
1492                              "", &opts);
1493                diffcore_std(&opts);
1494                diff_flush(&opts);
1495        }
1496
1497        if (is_interactive(&options))
1498                goto run_rebase;
1499
1500        /* Detach HEAD and reset the tree */
1501        if (options.flags & REBASE_NO_QUIET)
1502                printf(_("First, rewinding head to replay your work on top of "
1503                         "it...\n"));
1504
1505        strbuf_addf(&msg, "rebase: checkout %s", options.onto_name);
1506        if (reset_head(&options.onto->object.oid, "checkout", NULL, 1,
1507            NULL, msg.buf))
1508                die(_("Could not detach HEAD"));
1509        strbuf_release(&msg);
1510
1511        /*
1512         * If the onto is a proper descendant of the tip of the branch, then
1513         * we just fast-forwarded.
1514         */
1515        strbuf_reset(&msg);
1516        if (!oidcmp(&merge_base, &options.orig_head)) {
1517                printf(_("Fast-forwarded %s to %s. \n"),
1518                        branch_name, options.onto_name);
1519                strbuf_addf(&msg, "rebase finished: %s onto %s",
1520                        options.head_name ? options.head_name : "detached HEAD",
1521                        oid_to_hex(&options.onto->object.oid));
1522                reset_head(NULL, "Fast-forwarded", options.head_name, 0,
1523                           "HEAD", msg.buf);
1524                strbuf_release(&msg);
1525                ret = !!finish_rebase(&options);
1526                goto cleanup;
1527        }
1528
1529        strbuf_addf(&revisions, "%s..%s",
1530                    options.root ? oid_to_hex(&options.onto->object.oid) :
1531                    (options.restrict_revision ?
1532                     oid_to_hex(&options.restrict_revision->object.oid) :
1533                     oid_to_hex(&options.upstream->object.oid)),
1534                    oid_to_hex(&options.orig_head));
1535
1536        options.revisions = revisions.buf;
1537
1538run_rebase:
1539        ret = !!run_specific_rebase(&options);
1540
1541cleanup:
1542        strbuf_release(&revisions);
1543        free(options.head_name);
1544        free(options.gpg_sign_opt);
1545        free(options.cmd);
1546        free(squash_onto_name);
1547        return ret;
1548}