3c8b29d82cd932b3724fa091f5f25b9bb7745921
   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
  66static int apply_autostash(void)
  67{
  68        warning("TODO");
  69        return 0;
  70}
  71
  72struct rebase_options {
  73        enum rebase_type type;
  74        const char *state_dir;
  75        struct commit *upstream;
  76        const char *upstream_name;
  77        const char *upstream_arg;
  78        char *head_name;
  79        struct object_id orig_head;
  80        struct commit *onto;
  81        const char *onto_name;
  82        const char *revisions;
  83        const char *switch_to;
  84        int root;
  85        struct commit *restrict_revision;
  86        int dont_finish_rebase;
  87        enum {
  88                REBASE_NO_QUIET = 1<<0,
  89                REBASE_VERBOSE = 1<<1,
  90                REBASE_DIFFSTAT = 1<<2,
  91                REBASE_FORCE = 1<<3,
  92                REBASE_INTERACTIVE_EXPLICIT = 1<<4,
  93        } flags;
  94        struct strbuf git_am_opt;
  95        const char *action;
  96        int signoff;
  97};
  98
  99static int is_interactive(struct rebase_options *opts)
 100{
 101        return opts->type == REBASE_INTERACTIVE ||
 102                opts->type == REBASE_PRESERVE_MERGES;
 103}
 104
 105/* Returns the filename prefixed by the state_dir */
 106static const char *state_dir_path(const char *filename, struct rebase_options *opts)
 107{
 108        static struct strbuf path = STRBUF_INIT;
 109        static size_t prefix_len;
 110
 111        if (!prefix_len) {
 112                strbuf_addf(&path, "%s/", opts->state_dir);
 113                prefix_len = path.len;
 114        }
 115
 116        strbuf_setlen(&path, prefix_len);
 117        strbuf_addstr(&path, filename);
 118        return path.buf;
 119}
 120
 121/* Read one file, then strip line endings */
 122static int read_one(const char *path, struct strbuf *buf)
 123{
 124        if (strbuf_read_file(buf, path, 0) < 0)
 125                return error_errno(_("could not read '%s'"), path);
 126        strbuf_trim_trailing_newline(buf);
 127        return 0;
 128}
 129
 130/* Initialize the rebase options from the state directory. */
 131static int read_basic_state(struct rebase_options *opts)
 132{
 133        struct strbuf head_name = STRBUF_INIT;
 134        struct strbuf buf = STRBUF_INIT;
 135        struct object_id oid;
 136
 137        if (read_one(state_dir_path("head-name", opts), &head_name) ||
 138            read_one(state_dir_path("onto", opts), &buf))
 139                return -1;
 140        opts->head_name = starts_with(head_name.buf, "refs/") ?
 141                xstrdup(head_name.buf) : NULL;
 142        strbuf_release(&head_name);
 143        if (get_oid(buf.buf, &oid))
 144                return error(_("could not get 'onto': '%s'"), buf.buf);
 145        opts->onto = lookup_commit_or_die(&oid, buf.buf);
 146
 147        /*
 148         * We always write to orig-head, but interactive rebase used to write to
 149         * head. Fall back to reading from head to cover for the case that the
 150         * user upgraded git with an ongoing interactive rebase.
 151         */
 152        strbuf_reset(&buf);
 153        if (file_exists(state_dir_path("orig-head", opts))) {
 154                if (read_one(state_dir_path("orig-head", opts), &buf))
 155                        return -1;
 156        } else if (read_one(state_dir_path("head", opts), &buf))
 157                return -1;
 158        if (get_oid(buf.buf, &opts->orig_head))
 159                return error(_("invalid orig-head: '%s'"), buf.buf);
 160
 161        strbuf_reset(&buf);
 162        if (read_one(state_dir_path("quiet", opts), &buf))
 163                return -1;
 164        if (buf.len)
 165                opts->flags &= ~REBASE_NO_QUIET;
 166        else
 167                opts->flags |= REBASE_NO_QUIET;
 168
 169        if (file_exists(state_dir_path("verbose", opts)))
 170                opts->flags |= REBASE_VERBOSE;
 171
 172        if (file_exists(state_dir_path("signoff", opts))) {
 173                opts->signoff = 1;
 174                opts->flags |= REBASE_FORCE;
 175        }
 176
 177        strbuf_release(&buf);
 178
 179        return 0;
 180}
 181
 182static int finish_rebase(struct rebase_options *opts)
 183{
 184        struct strbuf dir = STRBUF_INIT;
 185        const char *argv_gc_auto[] = { "gc", "--auto", NULL };
 186
 187        delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
 188        apply_autostash();
 189        close_all_packs(the_repository->objects);
 190        /*
 191         * We ignore errors in 'gc --auto', since the
 192         * user should see them.
 193         */
 194        run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
 195        strbuf_addstr(&dir, opts->state_dir);
 196        remove_dir_recursively(&dir, 0);
 197        strbuf_release(&dir);
 198
 199        return 0;
 200}
 201
 202static struct commit *peel_committish(const char *name)
 203{
 204        struct object *obj;
 205        struct object_id oid;
 206
 207        if (get_oid(name, &oid))
 208                return NULL;
 209        obj = parse_object(the_repository, &oid);
 210        return (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
 211}
 212
 213static void add_var(struct strbuf *buf, const char *name, const char *value)
 214{
 215        if (!value)
 216                strbuf_addf(buf, "unset %s; ", name);
 217        else {
 218                strbuf_addf(buf, "%s=", name);
 219                sq_quote_buf(buf, value);
 220                strbuf_addstr(buf, "; ");
 221        }
 222}
 223
 224static int run_specific_rebase(struct rebase_options *opts)
 225{
 226        const char *argv[] = { NULL, NULL };
 227        struct strbuf script_snippet = STRBUF_INIT;
 228        int status;
 229        const char *backend, *backend_func;
 230
 231        add_var(&script_snippet, "GIT_DIR", absolute_path(get_git_dir()));
 232        add_var(&script_snippet, "state_dir", opts->state_dir);
 233
 234        add_var(&script_snippet, "upstream_name", opts->upstream_name);
 235        add_var(&script_snippet, "upstream", opts->upstream ?
 236                oid_to_hex(&opts->upstream->object.oid) : NULL);
 237        add_var(&script_snippet, "head_name",
 238                opts->head_name ? opts->head_name : "detached HEAD");
 239        add_var(&script_snippet, "orig_head", oid_to_hex(&opts->orig_head));
 240        add_var(&script_snippet, "onto", opts->onto ?
 241                oid_to_hex(&opts->onto->object.oid) : NULL);
 242        add_var(&script_snippet, "onto_name", opts->onto_name);
 243        add_var(&script_snippet, "revisions", opts->revisions);
 244        add_var(&script_snippet, "restrict_revision", opts->restrict_revision ?
 245                oid_to_hex(&opts->restrict_revision->object.oid) : NULL);
 246        add_var(&script_snippet, "GIT_QUIET",
 247                opts->flags & REBASE_NO_QUIET ? "" : "t");
 248        add_var(&script_snippet, "git_am_opt", opts->git_am_opt.buf);
 249        add_var(&script_snippet, "verbose",
 250                opts->flags & REBASE_VERBOSE ? "t" : "");
 251        add_var(&script_snippet, "diffstat",
 252                opts->flags & REBASE_DIFFSTAT ? "t" : "");
 253        add_var(&script_snippet, "force_rebase",
 254                opts->flags & REBASE_FORCE ? "t" : "");
 255        if (opts->switch_to)
 256                add_var(&script_snippet, "switch_to", opts->switch_to);
 257        add_var(&script_snippet, "action", opts->action ? opts->action : "");
 258        add_var(&script_snippet, "signoff", opts->signoff ? "--signoff" : "");
 259
 260        switch (opts->type) {
 261        case REBASE_AM:
 262                backend = "git-rebase--am";
 263                backend_func = "git_rebase__am";
 264                break;
 265        case REBASE_INTERACTIVE:
 266                backend = "git-rebase--interactive";
 267                backend_func = "git_rebase__interactive";
 268                break;
 269        case REBASE_MERGE:
 270                backend = "git-rebase--merge";
 271                backend_func = "git_rebase__merge";
 272                break;
 273        case REBASE_PRESERVE_MERGES:
 274                backend = "git-rebase--preserve-merges";
 275                backend_func = "git_rebase__preserve_merges";
 276                break;
 277        default:
 278                BUG("Unhandled rebase type %d", opts->type);
 279                break;
 280        }
 281
 282        strbuf_addf(&script_snippet,
 283                    ". git-sh-setup && . git-rebase--common &&"
 284                    " . %s && %s", backend, backend_func);
 285        argv[0] = script_snippet.buf;
 286
 287        status = run_command_v_opt(argv, RUN_USING_SHELL);
 288        if (opts->dont_finish_rebase)
 289                ; /* do nothing */
 290        else if (status == 0) {
 291                if (!file_exists(state_dir_path("stopped-sha", opts)))
 292                        finish_rebase(opts);
 293        } else if (status == 2) {
 294                struct strbuf dir = STRBUF_INIT;
 295
 296                apply_autostash();
 297                strbuf_addstr(&dir, opts->state_dir);
 298                remove_dir_recursively(&dir, 0);
 299                strbuf_release(&dir);
 300                die("Nothing to do");
 301        }
 302
 303        strbuf_release(&script_snippet);
 304
 305        return status ? -1 : 0;
 306}
 307
 308#define GIT_REFLOG_ACTION_ENVIRONMENT "GIT_REFLOG_ACTION"
 309
 310static int reset_head(struct object_id *oid, const char *action,
 311                      const char *switch_to_branch, int detach_head)
 312{
 313        struct object_id head_oid;
 314        struct tree_desc desc;
 315        struct lock_file lock = LOCK_INIT;
 316        struct unpack_trees_options unpack_tree_opts;
 317        struct tree *tree;
 318        const char *reflog_action;
 319        struct strbuf msg = STRBUF_INIT;
 320        size_t prefix_len;
 321        struct object_id *orig = NULL, oid_orig,
 322                *old_orig = NULL, oid_old_orig;
 323        int ret = 0;
 324
 325        if (switch_to_branch && !starts_with(switch_to_branch, "refs/"))
 326                BUG("Not a fully qualified branch: '%s'", switch_to_branch);
 327
 328        if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
 329                return -1;
 330
 331        if (!oid) {
 332                if (get_oid("HEAD", &head_oid)) {
 333                        rollback_lock_file(&lock);
 334                        return error(_("could not determine HEAD revision"));
 335                }
 336                oid = &head_oid;
 337        }
 338
 339        memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
 340        setup_unpack_trees_porcelain(&unpack_tree_opts, action);
 341        unpack_tree_opts.head_idx = 1;
 342        unpack_tree_opts.src_index = the_repository->index;
 343        unpack_tree_opts.dst_index = the_repository->index;
 344        unpack_tree_opts.fn = oneway_merge;
 345        unpack_tree_opts.update = 1;
 346        unpack_tree_opts.merge = 1;
 347        if (!detach_head)
 348                unpack_tree_opts.reset = 1;
 349
 350        if (read_index_unmerged(the_repository->index) < 0) {
 351                rollback_lock_file(&lock);
 352                return error(_("could not read index"));
 353        }
 354
 355        if (!fill_tree_descriptor(&desc, oid)) {
 356                error(_("failed to find tree of %s"), oid_to_hex(oid));
 357                rollback_lock_file(&lock);
 358                free((void *)desc.buffer);
 359                return -1;
 360        }
 361
 362        if (unpack_trees(1, &desc, &unpack_tree_opts)) {
 363                rollback_lock_file(&lock);
 364                free((void *)desc.buffer);
 365                return -1;
 366        }
 367
 368        tree = parse_tree_indirect(oid);
 369        prime_cache_tree(the_repository->index, tree);
 370
 371        if (write_locked_index(the_repository->index, &lock, COMMIT_LOCK) < 0)
 372                ret = error(_("could not write index"));
 373        free((void *)desc.buffer);
 374
 375        if (ret)
 376                return ret;
 377
 378        reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
 379        strbuf_addf(&msg, "%s: ", reflog_action ? reflog_action : "rebase");
 380        prefix_len = msg.len;
 381
 382        if (!get_oid("ORIG_HEAD", &oid_old_orig))
 383                old_orig = &oid_old_orig;
 384        if (!get_oid("HEAD", &oid_orig)) {
 385                orig = &oid_orig;
 386                strbuf_addstr(&msg, "updating ORIG_HEAD");
 387                update_ref(msg.buf, "ORIG_HEAD", orig, old_orig, 0,
 388                           UPDATE_REFS_MSG_ON_ERR);
 389        } else if (old_orig)
 390                delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
 391        strbuf_setlen(&msg, prefix_len);
 392        strbuf_addstr(&msg, "updating HEAD");
 393        if (!switch_to_branch)
 394                ret = update_ref(msg.buf, "HEAD", oid, orig, REF_NO_DEREF,
 395                                 UPDATE_REFS_MSG_ON_ERR);
 396        else {
 397                ret = create_symref("HEAD", switch_to_branch, msg.buf);
 398                if (!ret)
 399                        ret = update_ref(msg.buf, "HEAD", oid, NULL, 0,
 400                                         UPDATE_REFS_MSG_ON_ERR);
 401        }
 402
 403        strbuf_release(&msg);
 404        return ret;
 405}
 406
 407static int rebase_config(const char *var, const char *value, void *data)
 408{
 409        struct rebase_options *opts = data;
 410
 411        if (!strcmp(var, "rebase.stat")) {
 412                if (git_config_bool(var, value))
 413                        opts->flags |= REBASE_DIFFSTAT;
 414                else
 415                        opts->flags &= !REBASE_DIFFSTAT;
 416                return 0;
 417        }
 418
 419        return git_default_config(var, value, data);
 420}
 421
 422/*
 423 * Determines whether the commits in from..to are linear, i.e. contain
 424 * no merge commits. This function *expects* `from` to be an ancestor of
 425 * `to`.
 426 */
 427static int is_linear_history(struct commit *from, struct commit *to)
 428{
 429        while (to && to != from) {
 430                parse_commit(to);
 431                if (!to->parents)
 432                        return 1;
 433                if (to->parents->next)
 434                        return 0;
 435                to = to->parents->item;
 436        }
 437        return 1;
 438}
 439
 440static int can_fast_forward(struct commit *onto, struct object_id *head_oid,
 441                            struct object_id *merge_base)
 442{
 443        struct commit *head = lookup_commit(the_repository, head_oid);
 444        struct commit_list *merge_bases;
 445        int res;
 446
 447        if (!head)
 448                return 0;
 449
 450        merge_bases = get_merge_bases(onto, head);
 451        if (merge_bases && !merge_bases->next) {
 452                oidcpy(merge_base, &merge_bases->item->object.oid);
 453                res = !oidcmp(merge_base, &onto->object.oid);
 454        } else {
 455                oidcpy(merge_base, &null_oid);
 456                res = 0;
 457        }
 458        free_commit_list(merge_bases);
 459        return res && is_linear_history(onto, head);
 460}
 461
 462/* -i followed by -m is still -i */
 463static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
 464{
 465        struct rebase_options *opts = opt->value;
 466
 467        if (!is_interactive(opts))
 468                opts->type = REBASE_MERGE;
 469
 470        return 0;
 471}
 472
 473/* -i followed by -p is still explicitly interactive, but -p alone is not */
 474static int parse_opt_interactive(const struct option *opt, const char *arg,
 475                                 int unset)
 476{
 477        struct rebase_options *opts = opt->value;
 478
 479        opts->type = REBASE_INTERACTIVE;
 480        opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
 481
 482        return 0;
 483}
 484
 485int cmd_rebase(int argc, const char **argv, const char *prefix)
 486{
 487        struct rebase_options options = {
 488                .type = REBASE_UNSPECIFIED,
 489                .flags = REBASE_NO_QUIET,
 490                .git_am_opt = STRBUF_INIT,
 491        };
 492        const char *branch_name;
 493        int ret, flags, total_argc, in_progress = 0;
 494        int ok_to_skip_pre_rebase = 0;
 495        struct strbuf msg = STRBUF_INIT;
 496        struct strbuf revisions = STRBUF_INIT;
 497        struct strbuf buf = STRBUF_INIT;
 498        struct object_id merge_base;
 499        enum {
 500                NO_ACTION,
 501                ACTION_CONTINUE,
 502                ACTION_SKIP,
 503                ACTION_ABORT,
 504                ACTION_QUIT,
 505                ACTION_EDIT_TODO,
 506                ACTION_SHOW_CURRENT_PATCH,
 507        } action = NO_ACTION;
 508        struct option builtin_rebase_options[] = {
 509                OPT_STRING(0, "onto", &options.onto_name,
 510                           N_("revision"),
 511                           N_("rebase onto given branch instead of upstream")),
 512                OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
 513                         N_("allow pre-rebase hook to run")),
 514                OPT_NEGBIT('q', "quiet", &options.flags,
 515                           N_("be quiet. implies --no-stat"),
 516                           REBASE_NO_QUIET| REBASE_VERBOSE | REBASE_DIFFSTAT),
 517                OPT_BIT('v', "verbose", &options.flags,
 518                        N_("display a diffstat of what changed upstream"),
 519                        REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
 520                {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
 521                        N_("do not show diffstat of what changed upstream"),
 522                        PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
 523                OPT_BOOL(0, "signoff", &options.signoff,
 524                         N_("add a Signed-off-by: line to each commit")),
 525                OPT_BIT('f', "force-rebase", &options.flags,
 526                        N_("cherry-pick all commits, even if unchanged"),
 527                        REBASE_FORCE),
 528                OPT_BIT(0, "no-ff", &options.flags,
 529                        N_("cherry-pick all commits, even if unchanged"),
 530                        REBASE_FORCE),
 531                OPT_CMDMODE(0, "continue", &action, N_("continue"),
 532                            ACTION_CONTINUE),
 533                OPT_CMDMODE(0, "skip", &action,
 534                            N_("skip current patch and continue"), ACTION_SKIP),
 535                OPT_CMDMODE(0, "abort", &action,
 536                            N_("abort and check out the original branch"),
 537                            ACTION_ABORT),
 538                OPT_CMDMODE(0, "quit", &action,
 539                            N_("abort but keep HEAD where it is"), ACTION_QUIT),
 540                OPT_CMDMODE(0, "edit-todo", &action, N_("edit the todo list "
 541                            "during an interactive rebase"), ACTION_EDIT_TODO),
 542                OPT_CMDMODE(0, "show-current-patch", &action,
 543                            N_("show the patch file being applied or merged"),
 544                            ACTION_SHOW_CURRENT_PATCH),
 545                { OPTION_CALLBACK, 'm', "merge", &options, NULL,
 546                        N_("use merging strategies to rebase"),
 547                        PARSE_OPT_NOARG | PARSE_OPT_NONEG,
 548                        parse_opt_merge },
 549                { OPTION_CALLBACK, 'i', "interactive", &options, NULL,
 550                        N_("let the user edit the list of commits to rebase"),
 551                        PARSE_OPT_NOARG | PARSE_OPT_NONEG,
 552                        parse_opt_interactive },
 553                OPT_SET_INT('p', "preserve-merges", &options.type,
 554                            N_("try to recreate merges instead of ignoring "
 555                               "them"), REBASE_PRESERVE_MERGES),
 556                OPT_END(),
 557        };
 558
 559        /*
 560         * NEEDSWORK: Once the builtin rebase has been tested enough
 561         * and git-legacy-rebase.sh is retired to contrib/, this preamble
 562         * can be removed.
 563         */
 564
 565        if (!use_builtin_rebase()) {
 566                const char *path = mkpath("%s/git-legacy-rebase",
 567                                          git_exec_path());
 568
 569                if (sane_execvp(path, (char **)argv) < 0)
 570                        die_errno(_("could not exec %s"), path);
 571                else
 572                        BUG("sane_execvp() returned???");
 573        }
 574
 575        if (argc == 2 && !strcmp(argv[1], "-h"))
 576                usage_with_options(builtin_rebase_usage,
 577                                   builtin_rebase_options);
 578
 579        prefix = setup_git_directory();
 580        trace_repo_setup(prefix);
 581        setup_work_tree();
 582
 583        git_config(rebase_config, &options);
 584
 585        strbuf_reset(&buf);
 586        strbuf_addf(&buf, "%s/applying", apply_dir());
 587        if(file_exists(buf.buf))
 588                die(_("It looks like 'git am' is in progress. Cannot rebase."));
 589
 590        if (is_directory(apply_dir())) {
 591                options.type = REBASE_AM;
 592                options.state_dir = apply_dir();
 593        } else if (is_directory(merge_dir())) {
 594                strbuf_reset(&buf);
 595                strbuf_addf(&buf, "%s/rewritten", merge_dir());
 596                if (is_directory(buf.buf)) {
 597                        options.type = REBASE_PRESERVE_MERGES;
 598                        options.flags |= REBASE_INTERACTIVE_EXPLICIT;
 599                } else {
 600                        strbuf_reset(&buf);
 601                        strbuf_addf(&buf, "%s/interactive", merge_dir());
 602                        if(file_exists(buf.buf)) {
 603                                options.type = REBASE_INTERACTIVE;
 604                                options.flags |= REBASE_INTERACTIVE_EXPLICIT;
 605                        } else
 606                                options.type = REBASE_MERGE;
 607                }
 608                options.state_dir = merge_dir();
 609        }
 610
 611        if (options.type != REBASE_UNSPECIFIED)
 612                in_progress = 1;
 613
 614        total_argc = argc;
 615        argc = parse_options(argc, argv, prefix,
 616                             builtin_rebase_options,
 617                             builtin_rebase_usage, 0);
 618
 619        if (action != NO_ACTION && total_argc != 2) {
 620                usage_with_options(builtin_rebase_usage,
 621                                   builtin_rebase_options);
 622        }
 623
 624        if (argc > 2)
 625                usage_with_options(builtin_rebase_usage,
 626                                   builtin_rebase_options);
 627
 628        if (action != NO_ACTION && !in_progress)
 629                die(_("No rebase in progress?"));
 630
 631        if (action == ACTION_EDIT_TODO && !is_interactive(&options))
 632                die(_("The --edit-todo action can only be used during "
 633                      "interactive rebase."));
 634
 635        switch (action) {
 636        case ACTION_CONTINUE: {
 637                struct object_id head;
 638                struct lock_file lock_file = LOCK_INIT;
 639                int fd;
 640
 641                options.action = "continue";
 642
 643                /* Sanity check */
 644                if (get_oid("HEAD", &head))
 645                        die(_("Cannot read HEAD"));
 646
 647                fd = hold_locked_index(&lock_file, 0);
 648                if (read_index(the_repository->index) < 0)
 649                        die(_("could not read index"));
 650                refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
 651                              NULL);
 652                if (0 <= fd)
 653                        update_index_if_able(the_repository->index,
 654                                             &lock_file);
 655                rollback_lock_file(&lock_file);
 656
 657                if (has_unstaged_changes(1)) {
 658                        puts(_("You must edit all merge conflicts and then\n"
 659                               "mark them as resolved using git add"));
 660                        exit(1);
 661                }
 662                if (read_basic_state(&options))
 663                        exit(1);
 664                goto run_rebase;
 665        }
 666        case ACTION_SKIP: {
 667                struct string_list merge_rr = STRING_LIST_INIT_DUP;
 668
 669                options.action = "skip";
 670
 671                rerere_clear(&merge_rr);
 672                string_list_clear(&merge_rr, 1);
 673
 674                if (reset_head(NULL, "reset", NULL, 0) < 0)
 675                        die(_("could not discard worktree changes"));
 676                if (read_basic_state(&options))
 677                        exit(1);
 678                goto run_rebase;
 679        }
 680        case ACTION_ABORT: {
 681                struct string_list merge_rr = STRING_LIST_INIT_DUP;
 682                options.action = "abort";
 683
 684                rerere_clear(&merge_rr);
 685                string_list_clear(&merge_rr, 1);
 686
 687                if (read_basic_state(&options))
 688                        exit(1);
 689                if (reset_head(&options.orig_head, "reset",
 690                               options.head_name, 0) < 0)
 691                        die(_("could not move back to %s"),
 692                            oid_to_hex(&options.orig_head));
 693                ret = finish_rebase(&options);
 694                goto cleanup;
 695        }
 696        case ACTION_QUIT: {
 697                strbuf_reset(&buf);
 698                strbuf_addstr(&buf, options.state_dir);
 699                ret = !!remove_dir_recursively(&buf, 0);
 700                if (ret)
 701                        die(_("could not remove '%s'"), options.state_dir);
 702                goto cleanup;
 703        }
 704        case ACTION_EDIT_TODO:
 705                options.action = "edit-todo";
 706                options.dont_finish_rebase = 1;
 707                goto run_rebase;
 708        case ACTION_SHOW_CURRENT_PATCH:
 709                options.action = "show-current-patch";
 710                options.dont_finish_rebase = 1;
 711                goto run_rebase;
 712        case NO_ACTION:
 713                break;
 714        default:
 715                BUG("action: %d", action);
 716        }
 717
 718        /* Make sure no rebase is in progress */
 719        if (in_progress) {
 720                const char *last_slash = strrchr(options.state_dir, '/');
 721                const char *state_dir_base =
 722                        last_slash ? last_slash + 1 : options.state_dir;
 723                const char *cmd_live_rebase =
 724                        "git rebase (--continue | --abort | --skip)";
 725                strbuf_reset(&buf);
 726                strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
 727                die(_("It seems that there is already a %s directory, and\n"
 728                      "I wonder if you are in the middle of another rebase.  "
 729                      "If that is the\n"
 730                      "case, please try\n\t%s\n"
 731                      "If that is not the case, please\n\t%s\n"
 732                      "and run me again.  I am stopping in case you still "
 733                      "have something\n"
 734                      "valuable there.\n"),
 735                    state_dir_base, cmd_live_rebase, buf.buf);
 736        }
 737
 738        if (!(options.flags & REBASE_NO_QUIET))
 739                strbuf_addstr(&options.git_am_opt, " -q");
 740
 741        switch (options.type) {
 742        case REBASE_MERGE:
 743        case REBASE_INTERACTIVE:
 744        case REBASE_PRESERVE_MERGES:
 745                options.state_dir = merge_dir();
 746                break;
 747        case REBASE_AM:
 748                options.state_dir = apply_dir();
 749                break;
 750        default:
 751                /* the default rebase backend is `--am` */
 752                options.type = REBASE_AM;
 753                options.state_dir = apply_dir();
 754                break;
 755        }
 756
 757        if (options.signoff) {
 758                if (options.type == REBASE_PRESERVE_MERGES)
 759                        die("cannot combine '--signoff' with "
 760                            "'--preserve-merges'");
 761                strbuf_addstr(&options.git_am_opt, " --signoff");
 762                options.flags |= REBASE_FORCE;
 763        }
 764
 765        if (!options.root) {
 766                if (argc < 1)
 767                        die("TODO: handle @{upstream}");
 768                else {
 769                        options.upstream_name = argv[0];
 770                        argc--;
 771                        argv++;
 772                        if (!strcmp(options.upstream_name, "-"))
 773                                options.upstream_name = "@{-1}";
 774                }
 775                options.upstream = peel_committish(options.upstream_name);
 776                if (!options.upstream)
 777                        die(_("invalid upstream '%s'"), options.upstream_name);
 778                options.upstream_arg = options.upstream_name;
 779        } else
 780                die("TODO: upstream for --root");
 781
 782        /* Make sure the branch to rebase onto is valid. */
 783        if (!options.onto_name)
 784                options.onto_name = options.upstream_name;
 785        if (strstr(options.onto_name, "...")) {
 786                if (get_oid_mb(options.onto_name, &merge_base) < 0)
 787                        die(_("'%s': need exactly one merge base"),
 788                            options.onto_name);
 789                options.onto = lookup_commit_or_die(&merge_base,
 790                                                    options.onto_name);
 791        } else {
 792                options.onto = peel_committish(options.onto_name);
 793                if (!options.onto)
 794                        die(_("Does not point to a valid commit '%s'"),
 795                                options.onto_name);
 796        }
 797
 798        /*
 799         * If the branch to rebase is given, that is the branch we will rebase
 800         * branch_name -- branch/commit being rebased, or
 801         *                HEAD (already detached)
 802         * orig_head -- commit object name of tip of the branch before rebasing
 803         * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
 804         */
 805        if (argc == 1) {
 806                /* Is it "rebase other branchname" or "rebase other commit"? */
 807                branch_name = argv[0];
 808                options.switch_to = argv[0];
 809
 810                /* Is it a local branch? */
 811                strbuf_reset(&buf);
 812                strbuf_addf(&buf, "refs/heads/%s", branch_name);
 813                if (!read_ref(buf.buf, &options.orig_head))
 814                        options.head_name = xstrdup(buf.buf);
 815                /* If not is it a valid ref (branch or commit)? */
 816                else if (!get_oid(branch_name, &options.orig_head))
 817                        options.head_name = NULL;
 818                else
 819                        die(_("fatal: no such branch/commit '%s'"),
 820                            branch_name);
 821        } else if (argc == 0) {
 822                /* Do not need to switch branches, we are already on it. */
 823                options.head_name =
 824                        xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
 825                                         &flags));
 826                if (!options.head_name)
 827                        die(_("No such ref: %s"), "HEAD");
 828                if (flags & REF_ISSYMREF) {
 829                        if (!skip_prefix(options.head_name,
 830                                         "refs/heads/", &branch_name))
 831                                branch_name = options.head_name;
 832
 833                } else {
 834                        free(options.head_name);
 835                        options.head_name = NULL;
 836                        branch_name = "HEAD";
 837                }
 838                if (get_oid("HEAD", &options.orig_head))
 839                        die(_("Could not resolve HEAD to a revision"));
 840        } else
 841                BUG("unexpected number of arguments left to parse");
 842
 843        if (read_index(the_repository->index) < 0)
 844                die(_("could not read index"));
 845
 846        if (require_clean_work_tree("rebase",
 847                                    _("Please commit or stash them."), 1, 1)) {
 848                ret = 1;
 849                goto cleanup;
 850        }
 851
 852        /*
 853         * Now we are rebasing commits upstream..orig_head (or with --root,
 854         * everything leading up to orig_head) on top of onto.
 855         */
 856
 857        /*
 858         * Check if we are already based on onto with linear history,
 859         * but this should be done only when upstream and onto are the same
 860         * and if this is not an interactive rebase.
 861         */
 862        if (can_fast_forward(options.onto, &options.orig_head, &merge_base) &&
 863            !is_interactive(&options) && !options.restrict_revision &&
 864            !oidcmp(&options.upstream->object.oid, &options.onto->object.oid)) {
 865                int flag;
 866
 867                if (!(options.flags & REBASE_FORCE)) {
 868                        /* Lazily switch to the target branch if needed... */
 869                        if (options.switch_to) {
 870                                struct object_id oid;
 871
 872                                if (get_oid(options.switch_to, &oid) < 0) {
 873                                        ret = !!error(_("could not parse '%s'"),
 874                                                      options.switch_to);
 875                                        goto cleanup;
 876                                }
 877
 878                                strbuf_reset(&buf);
 879                                strbuf_addf(&buf, "rebase: checkout %s",
 880                                            options.switch_to);
 881                                if (reset_head(&oid, "checkout",
 882                                               options.head_name, 0) < 0) {
 883                                        ret = !!error(_("could not switch to "
 884                                                        "%s"),
 885                                                      options.switch_to);
 886                                        goto cleanup;
 887                                }
 888                        }
 889
 890                        if (!(options.flags & REBASE_NO_QUIET))
 891                                ; /* be quiet */
 892                        else if (!strcmp(branch_name, "HEAD") &&
 893                                 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
 894                                puts(_("HEAD is up to date."));
 895                        else
 896                                printf(_("Current branch %s is up to date.\n"),
 897                                       branch_name);
 898                        ret = !!finish_rebase(&options);
 899                        goto cleanup;
 900                } else if (!(options.flags & REBASE_NO_QUIET))
 901                        ; /* be quiet */
 902                else if (!strcmp(branch_name, "HEAD") &&
 903                         resolve_ref_unsafe("HEAD", 0, NULL, &flag))
 904                        puts(_("HEAD is up to date, rebase forced."));
 905                else
 906                        printf(_("Current branch %s is up to date, rebase "
 907                                 "forced.\n"), branch_name);
 908        }
 909
 910        /* If a hook exists, give it a chance to interrupt*/
 911        if (!ok_to_skip_pre_rebase &&
 912            run_hook_le(NULL, "pre-rebase", options.upstream_arg,
 913                        argc ? argv[0] : NULL, NULL))
 914                die(_("The pre-rebase hook refused to rebase."));
 915
 916        if (options.flags & REBASE_DIFFSTAT) {
 917                struct diff_options opts;
 918
 919                if (options.flags & REBASE_VERBOSE)
 920                        printf(_("Changes from %s to %s:\n"),
 921                                oid_to_hex(&merge_base),
 922                                oid_to_hex(&options.onto->object.oid));
 923
 924                /* We want color (if set), but no pager */
 925                diff_setup(&opts);
 926                opts.stat_width = -1; /* use full terminal width */
 927                opts.stat_graph_width = -1; /* respect statGraphWidth config */
 928                opts.output_format |=
 929                        DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
 930                opts.detect_rename = DIFF_DETECT_RENAME;
 931                diff_setup_done(&opts);
 932                diff_tree_oid(&merge_base, &options.onto->object.oid,
 933                              "", &opts);
 934                diffcore_std(&opts);
 935                diff_flush(&opts);
 936        }
 937
 938        if (is_interactive(&options))
 939                goto run_rebase;
 940
 941        /* Detach HEAD and reset the tree */
 942        if (options.flags & REBASE_NO_QUIET)
 943                printf(_("First, rewinding head to replay your work on top of "
 944                         "it...\n"));
 945
 946        strbuf_addf(&msg, "rebase: checkout %s", options.onto_name);
 947        if (reset_head(&options.onto->object.oid, "checkout", NULL, 1))
 948                die(_("Could not detach HEAD"));
 949        strbuf_release(&msg);
 950
 951        strbuf_addf(&revisions, "%s..%s",
 952                    options.root ? oid_to_hex(&options.onto->object.oid) :
 953                    (options.restrict_revision ?
 954                     oid_to_hex(&options.restrict_revision->object.oid) :
 955                     oid_to_hex(&options.upstream->object.oid)),
 956                    oid_to_hex(&options.orig_head));
 957
 958        options.revisions = revisions.buf;
 959
 960run_rebase:
 961        ret = !!run_specific_rebase(&options);
 962
 963cleanup:
 964        strbuf_release(&revisions);
 965        free(options.head_name);
 966        return ret;
 967}