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