6ce50eae0f2ea7da89348f40ed5046c18ab8ab29
   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        int committer_date_is_author_date = 0;
 530        struct option builtin_rebase_options[] = {
 531                OPT_STRING(0, "onto", &options.onto_name,
 532                           N_("revision"),
 533                           N_("rebase onto given branch instead of upstream")),
 534                OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
 535                         N_("allow pre-rebase hook to run")),
 536                OPT_NEGBIT('q', "quiet", &options.flags,
 537                           N_("be quiet. implies --no-stat"),
 538                           REBASE_NO_QUIET| REBASE_VERBOSE | REBASE_DIFFSTAT),
 539                OPT_BIT('v', "verbose", &options.flags,
 540                        N_("display a diffstat of what changed upstream"),
 541                        REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
 542                {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
 543                        N_("do not show diffstat of what changed upstream"),
 544                        PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
 545                OPT_BOOL(0, "signoff", &options.signoff,
 546                         N_("add a Signed-off-by: line to each commit")),
 547                OPT_BOOL(0, "committer-date-is-author-date",
 548                         &committer_date_is_author_date,
 549                         N_("passed to 'git am'")),
 550                OPT_BIT('f', "force-rebase", &options.flags,
 551                        N_("cherry-pick all commits, even if unchanged"),
 552                        REBASE_FORCE),
 553                OPT_BIT(0, "no-ff", &options.flags,
 554                        N_("cherry-pick all commits, even if unchanged"),
 555                        REBASE_FORCE),
 556                OPT_CMDMODE(0, "continue", &action, N_("continue"),
 557                            ACTION_CONTINUE),
 558                OPT_CMDMODE(0, "skip", &action,
 559                            N_("skip current patch and continue"), ACTION_SKIP),
 560                OPT_CMDMODE(0, "abort", &action,
 561                            N_("abort and check out the original branch"),
 562                            ACTION_ABORT),
 563                OPT_CMDMODE(0, "quit", &action,
 564                            N_("abort but keep HEAD where it is"), ACTION_QUIT),
 565                OPT_CMDMODE(0, "edit-todo", &action, N_("edit the todo list "
 566                            "during an interactive rebase"), ACTION_EDIT_TODO),
 567                OPT_CMDMODE(0, "show-current-patch", &action,
 568                            N_("show the patch file being applied or merged"),
 569                            ACTION_SHOW_CURRENT_PATCH),
 570                { OPTION_CALLBACK, 'm', "merge", &options, NULL,
 571                        N_("use merging strategies to rebase"),
 572                        PARSE_OPT_NOARG | PARSE_OPT_NONEG,
 573                        parse_opt_merge },
 574                { OPTION_CALLBACK, 'i', "interactive", &options, NULL,
 575                        N_("let the user edit the list of commits to rebase"),
 576                        PARSE_OPT_NOARG | PARSE_OPT_NONEG,
 577                        parse_opt_interactive },
 578                OPT_SET_INT('p', "preserve-merges", &options.type,
 579                            N_("try to recreate merges instead of ignoring "
 580                               "them"), REBASE_PRESERVE_MERGES),
 581                OPT_BOOL(0, "rerere-autoupdate",
 582                         &options.allow_rerere_autoupdate,
 583                         N_("allow rerere to update index  with resolved "
 584                            "conflict")),
 585                OPT_END(),
 586        };
 587
 588        /*
 589         * NEEDSWORK: Once the builtin rebase has been tested enough
 590         * and git-legacy-rebase.sh is retired to contrib/, this preamble
 591         * can be removed.
 592         */
 593
 594        if (!use_builtin_rebase()) {
 595                const char *path = mkpath("%s/git-legacy-rebase",
 596                                          git_exec_path());
 597
 598                if (sane_execvp(path, (char **)argv) < 0)
 599                        die_errno(_("could not exec %s"), path);
 600                else
 601                        BUG("sane_execvp() returned???");
 602        }
 603
 604        if (argc == 2 && !strcmp(argv[1], "-h"))
 605                usage_with_options(builtin_rebase_usage,
 606                                   builtin_rebase_options);
 607
 608        prefix = setup_git_directory();
 609        trace_repo_setup(prefix);
 610        setup_work_tree();
 611
 612        git_config(rebase_config, &options);
 613
 614        strbuf_reset(&buf);
 615        strbuf_addf(&buf, "%s/applying", apply_dir());
 616        if(file_exists(buf.buf))
 617                die(_("It looks like 'git am' is in progress. Cannot rebase."));
 618
 619        if (is_directory(apply_dir())) {
 620                options.type = REBASE_AM;
 621                options.state_dir = apply_dir();
 622        } else if (is_directory(merge_dir())) {
 623                strbuf_reset(&buf);
 624                strbuf_addf(&buf, "%s/rewritten", merge_dir());
 625                if (is_directory(buf.buf)) {
 626                        options.type = REBASE_PRESERVE_MERGES;
 627                        options.flags |= REBASE_INTERACTIVE_EXPLICIT;
 628                } else {
 629                        strbuf_reset(&buf);
 630                        strbuf_addf(&buf, "%s/interactive", merge_dir());
 631                        if(file_exists(buf.buf)) {
 632                                options.type = REBASE_INTERACTIVE;
 633                                options.flags |= REBASE_INTERACTIVE_EXPLICIT;
 634                        } else
 635                                options.type = REBASE_MERGE;
 636                }
 637                options.state_dir = merge_dir();
 638        }
 639
 640        if (options.type != REBASE_UNSPECIFIED)
 641                in_progress = 1;
 642
 643        total_argc = argc;
 644        argc = parse_options(argc, argv, prefix,
 645                             builtin_rebase_options,
 646                             builtin_rebase_usage, 0);
 647
 648        if (action != NO_ACTION && total_argc != 2) {
 649                usage_with_options(builtin_rebase_usage,
 650                                   builtin_rebase_options);
 651        }
 652
 653        if (argc > 2)
 654                usage_with_options(builtin_rebase_usage,
 655                                   builtin_rebase_options);
 656
 657        if (action != NO_ACTION && !in_progress)
 658                die(_("No rebase in progress?"));
 659
 660        if (action == ACTION_EDIT_TODO && !is_interactive(&options))
 661                die(_("The --edit-todo action can only be used during "
 662                      "interactive rebase."));
 663
 664        switch (action) {
 665        case ACTION_CONTINUE: {
 666                struct object_id head;
 667                struct lock_file lock_file = LOCK_INIT;
 668                int fd;
 669
 670                options.action = "continue";
 671
 672                /* Sanity check */
 673                if (get_oid("HEAD", &head))
 674                        die(_("Cannot read HEAD"));
 675
 676                fd = hold_locked_index(&lock_file, 0);
 677                if (read_index(the_repository->index) < 0)
 678                        die(_("could not read index"));
 679                refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
 680                              NULL);
 681                if (0 <= fd)
 682                        update_index_if_able(the_repository->index,
 683                                             &lock_file);
 684                rollback_lock_file(&lock_file);
 685
 686                if (has_unstaged_changes(1)) {
 687                        puts(_("You must edit all merge conflicts and then\n"
 688                               "mark them as resolved using git add"));
 689                        exit(1);
 690                }
 691                if (read_basic_state(&options))
 692                        exit(1);
 693                goto run_rebase;
 694        }
 695        case ACTION_SKIP: {
 696                struct string_list merge_rr = STRING_LIST_INIT_DUP;
 697
 698                options.action = "skip";
 699
 700                rerere_clear(&merge_rr);
 701                string_list_clear(&merge_rr, 1);
 702
 703                if (reset_head(NULL, "reset", NULL, 0) < 0)
 704                        die(_("could not discard worktree changes"));
 705                if (read_basic_state(&options))
 706                        exit(1);
 707                goto run_rebase;
 708        }
 709        case ACTION_ABORT: {
 710                struct string_list merge_rr = STRING_LIST_INIT_DUP;
 711                options.action = "abort";
 712
 713                rerere_clear(&merge_rr);
 714                string_list_clear(&merge_rr, 1);
 715
 716                if (read_basic_state(&options))
 717                        exit(1);
 718                if (reset_head(&options.orig_head, "reset",
 719                               options.head_name, 0) < 0)
 720                        die(_("could not move back to %s"),
 721                            oid_to_hex(&options.orig_head));
 722                ret = finish_rebase(&options);
 723                goto cleanup;
 724        }
 725        case ACTION_QUIT: {
 726                strbuf_reset(&buf);
 727                strbuf_addstr(&buf, options.state_dir);
 728                ret = !!remove_dir_recursively(&buf, 0);
 729                if (ret)
 730                        die(_("could not remove '%s'"), options.state_dir);
 731                goto cleanup;
 732        }
 733        case ACTION_EDIT_TODO:
 734                options.action = "edit-todo";
 735                options.dont_finish_rebase = 1;
 736                goto run_rebase;
 737        case ACTION_SHOW_CURRENT_PATCH:
 738                options.action = "show-current-patch";
 739                options.dont_finish_rebase = 1;
 740                goto run_rebase;
 741        case NO_ACTION:
 742                break;
 743        default:
 744                BUG("action: %d", action);
 745        }
 746
 747        /* Make sure no rebase is in progress */
 748        if (in_progress) {
 749                const char *last_slash = strrchr(options.state_dir, '/');
 750                const char *state_dir_base =
 751                        last_slash ? last_slash + 1 : options.state_dir;
 752                const char *cmd_live_rebase =
 753                        "git rebase (--continue | --abort | --skip)";
 754                strbuf_reset(&buf);
 755                strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
 756                die(_("It seems that there is already a %s directory, and\n"
 757                      "I wonder if you are in the middle of another rebase.  "
 758                      "If that is the\n"
 759                      "case, please try\n\t%s\n"
 760                      "If that is not the case, please\n\t%s\n"
 761                      "and run me again.  I am stopping in case you still "
 762                      "have something\n"
 763                      "valuable there.\n"),
 764                    state_dir_base, cmd_live_rebase, buf.buf);
 765        }
 766
 767        if (!(options.flags & REBASE_NO_QUIET))
 768                strbuf_addstr(&options.git_am_opt, " -q");
 769
 770        if (committer_date_is_author_date) {
 771                strbuf_addstr(&options.git_am_opt,
 772                              " --committer-date-is-author-date");
 773                options.flags |= REBASE_FORCE;
 774        }
 775
 776        switch (options.type) {
 777        case REBASE_MERGE:
 778        case REBASE_INTERACTIVE:
 779        case REBASE_PRESERVE_MERGES:
 780                options.state_dir = merge_dir();
 781                break;
 782        case REBASE_AM:
 783                options.state_dir = apply_dir();
 784                break;
 785        default:
 786                /* the default rebase backend is `--am` */
 787                options.type = REBASE_AM;
 788                options.state_dir = apply_dir();
 789                break;
 790        }
 791
 792        if (options.signoff) {
 793                if (options.type == REBASE_PRESERVE_MERGES)
 794                        die("cannot combine '--signoff' with "
 795                            "'--preserve-merges'");
 796                strbuf_addstr(&options.git_am_opt, " --signoff");
 797                options.flags |= REBASE_FORCE;
 798        }
 799
 800        if (!options.root) {
 801                if (argc < 1)
 802                        die("TODO: handle @{upstream}");
 803                else {
 804                        options.upstream_name = argv[0];
 805                        argc--;
 806                        argv++;
 807                        if (!strcmp(options.upstream_name, "-"))
 808                                options.upstream_name = "@{-1}";
 809                }
 810                options.upstream = peel_committish(options.upstream_name);
 811                if (!options.upstream)
 812                        die(_("invalid upstream '%s'"), options.upstream_name);
 813                options.upstream_arg = options.upstream_name;
 814        } else
 815                die("TODO: upstream for --root");
 816
 817        /* Make sure the branch to rebase onto is valid. */
 818        if (!options.onto_name)
 819                options.onto_name = options.upstream_name;
 820        if (strstr(options.onto_name, "...")) {
 821                if (get_oid_mb(options.onto_name, &merge_base) < 0)
 822                        die(_("'%s': need exactly one merge base"),
 823                            options.onto_name);
 824                options.onto = lookup_commit_or_die(&merge_base,
 825                                                    options.onto_name);
 826        } else {
 827                options.onto = peel_committish(options.onto_name);
 828                if (!options.onto)
 829                        die(_("Does not point to a valid commit '%s'"),
 830                                options.onto_name);
 831        }
 832
 833        /*
 834         * If the branch to rebase is given, that is the branch we will rebase
 835         * branch_name -- branch/commit being rebased, or
 836         *                HEAD (already detached)
 837         * orig_head -- commit object name of tip of the branch before rebasing
 838         * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
 839         */
 840        if (argc == 1) {
 841                /* Is it "rebase other branchname" or "rebase other commit"? */
 842                branch_name = argv[0];
 843                options.switch_to = argv[0];
 844
 845                /* Is it a local branch? */
 846                strbuf_reset(&buf);
 847                strbuf_addf(&buf, "refs/heads/%s", branch_name);
 848                if (!read_ref(buf.buf, &options.orig_head))
 849                        options.head_name = xstrdup(buf.buf);
 850                /* If not is it a valid ref (branch or commit)? */
 851                else if (!get_oid(branch_name, &options.orig_head))
 852                        options.head_name = NULL;
 853                else
 854                        die(_("fatal: no such branch/commit '%s'"),
 855                            branch_name);
 856        } else if (argc == 0) {
 857                /* Do not need to switch branches, we are already on it. */
 858                options.head_name =
 859                        xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
 860                                         &flags));
 861                if (!options.head_name)
 862                        die(_("No such ref: %s"), "HEAD");
 863                if (flags & REF_ISSYMREF) {
 864                        if (!skip_prefix(options.head_name,
 865                                         "refs/heads/", &branch_name))
 866                                branch_name = options.head_name;
 867
 868                } else {
 869                        free(options.head_name);
 870                        options.head_name = NULL;
 871                        branch_name = "HEAD";
 872                }
 873                if (get_oid("HEAD", &options.orig_head))
 874                        die(_("Could not resolve HEAD to a revision"));
 875        } else
 876                BUG("unexpected number of arguments left to parse");
 877
 878        if (read_index(the_repository->index) < 0)
 879                die(_("could not read index"));
 880
 881        if (require_clean_work_tree("rebase",
 882                                    _("Please commit or stash them."), 1, 1)) {
 883                ret = 1;
 884                goto cleanup;
 885        }
 886
 887        /*
 888         * Now we are rebasing commits upstream..orig_head (or with --root,
 889         * everything leading up to orig_head) on top of onto.
 890         */
 891
 892        /*
 893         * Check if we are already based on onto with linear history,
 894         * but this should be done only when upstream and onto are the same
 895         * and if this is not an interactive rebase.
 896         */
 897        if (can_fast_forward(options.onto, &options.orig_head, &merge_base) &&
 898            !is_interactive(&options) && !options.restrict_revision &&
 899            !oidcmp(&options.upstream->object.oid, &options.onto->object.oid)) {
 900                int flag;
 901
 902                if (!(options.flags & REBASE_FORCE)) {
 903                        /* Lazily switch to the target branch if needed... */
 904                        if (options.switch_to) {
 905                                struct object_id oid;
 906
 907                                if (get_oid(options.switch_to, &oid) < 0) {
 908                                        ret = !!error(_("could not parse '%s'"),
 909                                                      options.switch_to);
 910                                        goto cleanup;
 911                                }
 912
 913                                strbuf_reset(&buf);
 914                                strbuf_addf(&buf, "rebase: checkout %s",
 915                                            options.switch_to);
 916                                if (reset_head(&oid, "checkout",
 917                                               options.head_name, 0) < 0) {
 918                                        ret = !!error(_("could not switch to "
 919                                                        "%s"),
 920                                                      options.switch_to);
 921                                        goto cleanup;
 922                                }
 923                        }
 924
 925                        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."));
 930                        else
 931                                printf(_("Current branch %s is up to date.\n"),
 932                                       branch_name);
 933                        ret = !!finish_rebase(&options);
 934                        goto cleanup;
 935                } else if (!(options.flags & REBASE_NO_QUIET))
 936                        ; /* be quiet */
 937                else if (!strcmp(branch_name, "HEAD") &&
 938                         resolve_ref_unsafe("HEAD", 0, NULL, &flag))
 939                        puts(_("HEAD is up to date, rebase forced."));
 940                else
 941                        printf(_("Current branch %s is up to date, rebase "
 942                                 "forced.\n"), branch_name);
 943        }
 944
 945        /* If a hook exists, give it a chance to interrupt*/
 946        if (!ok_to_skip_pre_rebase &&
 947            run_hook_le(NULL, "pre-rebase", options.upstream_arg,
 948                        argc ? argv[0] : NULL, NULL))
 949                die(_("The pre-rebase hook refused to rebase."));
 950
 951        if (options.flags & REBASE_DIFFSTAT) {
 952                struct diff_options opts;
 953
 954                if (options.flags & REBASE_VERBOSE)
 955                        printf(_("Changes from %s to %s:\n"),
 956                                oid_to_hex(&merge_base),
 957                                oid_to_hex(&options.onto->object.oid));
 958
 959                /* We want color (if set), but no pager */
 960                diff_setup(&opts);
 961                opts.stat_width = -1; /* use full terminal width */
 962                opts.stat_graph_width = -1; /* respect statGraphWidth config */
 963                opts.output_format |=
 964                        DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
 965                opts.detect_rename = DIFF_DETECT_RENAME;
 966                diff_setup_done(&opts);
 967                diff_tree_oid(&merge_base, &options.onto->object.oid,
 968                              "", &opts);
 969                diffcore_std(&opts);
 970                diff_flush(&opts);
 971        }
 972
 973        if (is_interactive(&options))
 974                goto run_rebase;
 975
 976        /* Detach HEAD and reset the tree */
 977        if (options.flags & REBASE_NO_QUIET)
 978                printf(_("First, rewinding head to replay your work on top of "
 979                         "it...\n"));
 980
 981        strbuf_addf(&msg, "rebase: checkout %s", options.onto_name);
 982        if (reset_head(&options.onto->object.oid, "checkout", NULL, 1))
 983                die(_("Could not detach HEAD"));
 984        strbuf_release(&msg);
 985
 986        strbuf_addf(&revisions, "%s..%s",
 987                    options.root ? oid_to_hex(&options.onto->object.oid) :
 988                    (options.restrict_revision ?
 989                     oid_to_hex(&options.restrict_revision->object.oid) :
 990                     oid_to_hex(&options.upstream->object.oid)),
 991                    oid_to_hex(&options.orig_head));
 992
 993        options.revisions = revisions.buf;
 994
 995run_rebase:
 996        ret = !!run_specific_rebase(&options);
 997
 998cleanup:
 999        strbuf_release(&revisions);
1000        free(options.head_name);
1001        return ret;
1002}