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