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