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