768bea0da8751228d3aa3acf1943aaefbe19666c
   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 "commit-reach.h"
  25#include "rerere.h"
  26#include "branch.h"
  27
  28static char const * const builtin_rebase_usage[] = {
  29        N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
  30                "[<upstream>] [<branch>]"),
  31        N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
  32                "--root [<branch>]"),
  33        N_("git rebase --continue | --abort | --skip | --edit-todo"),
  34        NULL
  35};
  36
  37static GIT_PATH_FUNC(apply_dir, "rebase-apply")
  38static GIT_PATH_FUNC(merge_dir, "rebase-merge")
  39
  40enum rebase_type {
  41        REBASE_UNSPECIFIED = -1,
  42        REBASE_AM,
  43        REBASE_MERGE,
  44        REBASE_INTERACTIVE,
  45        REBASE_PRESERVE_MERGES
  46};
  47
  48static int use_builtin_rebase(void)
  49{
  50        struct child_process cp = CHILD_PROCESS_INIT;
  51        struct strbuf out = STRBUF_INIT;
  52        int ret, env = git_env_bool("GIT_TEST_REBASE_USE_BUILTIN", -1);
  53
  54        if (env != -1)
  55                return env;
  56
  57        argv_array_pushl(&cp.args,
  58                         "config", "--bool", "rebase.usebuiltin", NULL);
  59        cp.git_cmd = 1;
  60        if (capture_command(&cp, &out, 6)) {
  61                strbuf_release(&out);
  62                return 1;
  63        }
  64
  65        strbuf_trim(&out);
  66        ret = !strcmp("true", out.buf);
  67        strbuf_release(&out);
  68        return ret;
  69}
  70
  71struct rebase_options {
  72        enum rebase_type type;
  73        const char *state_dir;
  74        struct commit *upstream;
  75        const char *upstream_name;
  76        const char *upstream_arg;
  77        char *head_name;
  78        struct object_id orig_head;
  79        struct commit *onto;
  80        const char *onto_name;
  81        const char *revisions;
  82        const char *switch_to;
  83        int root;
  84        struct object_id *squash_onto;
  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 argv_array git_am_opts;
  95        const char *action;
  96        int signoff;
  97        int allow_rerere_autoupdate;
  98        int keep_empty;
  99        int autosquash;
 100        char *gpg_sign_opt;
 101        int autostash;
 102        char *cmd;
 103        int allow_empty_message;
 104        int rebase_merges, rebase_cousins;
 105        char *strategy, *strategy_opts;
 106        struct strbuf git_format_patch_opt;
 107};
 108
 109static int is_interactive(struct rebase_options *opts)
 110{
 111        return opts->type == REBASE_INTERACTIVE ||
 112                opts->type == REBASE_PRESERVE_MERGES;
 113}
 114
 115static void imply_interactive(struct rebase_options *opts, const char *option)
 116{
 117        switch (opts->type) {
 118        case REBASE_AM:
 119                die(_("%s requires an interactive rebase"), option);
 120                break;
 121        case REBASE_INTERACTIVE:
 122        case REBASE_PRESERVE_MERGES:
 123                break;
 124        case REBASE_MERGE:
 125                /* we silently *upgrade* --merge to --interactive if needed */
 126        default:
 127                opts->type = REBASE_INTERACTIVE; /* implied */
 128                break;
 129        }
 130}
 131
 132/* Returns the filename prefixed by the state_dir */
 133static const char *state_dir_path(const char *filename, struct rebase_options *opts)
 134{
 135        static struct strbuf path = STRBUF_INIT;
 136        static size_t prefix_len;
 137
 138        if (!prefix_len) {
 139                strbuf_addf(&path, "%s/", opts->state_dir);
 140                prefix_len = path.len;
 141        }
 142
 143        strbuf_setlen(&path, prefix_len);
 144        strbuf_addstr(&path, filename);
 145        return path.buf;
 146}
 147
 148/* Read one file, then strip line endings */
 149static int read_one(const char *path, struct strbuf *buf)
 150{
 151        if (strbuf_read_file(buf, path, 0) < 0)
 152                return error_errno(_("could not read '%s'"), path);
 153        strbuf_trim_trailing_newline(buf);
 154        return 0;
 155}
 156
 157/* Initialize the rebase options from the state directory. */
 158static int read_basic_state(struct rebase_options *opts)
 159{
 160        struct strbuf head_name = STRBUF_INIT;
 161        struct strbuf buf = STRBUF_INIT;
 162        struct object_id oid;
 163
 164        if (read_one(state_dir_path("head-name", opts), &head_name) ||
 165            read_one(state_dir_path("onto", opts), &buf))
 166                return -1;
 167        opts->head_name = starts_with(head_name.buf, "refs/") ?
 168                xstrdup(head_name.buf) : NULL;
 169        strbuf_release(&head_name);
 170        if (get_oid(buf.buf, &oid))
 171                return error(_("could not get 'onto': '%s'"), buf.buf);
 172        opts->onto = lookup_commit_or_die(&oid, buf.buf);
 173
 174        /*
 175         * We always write to orig-head, but interactive rebase used to write to
 176         * head. Fall back to reading from head to cover for the case that the
 177         * user upgraded git with an ongoing interactive rebase.
 178         */
 179        strbuf_reset(&buf);
 180        if (file_exists(state_dir_path("orig-head", opts))) {
 181                if (read_one(state_dir_path("orig-head", opts), &buf))
 182                        return -1;
 183        } else if (read_one(state_dir_path("head", opts), &buf))
 184                return -1;
 185        if (get_oid(buf.buf, &opts->orig_head))
 186                return error(_("invalid orig-head: '%s'"), buf.buf);
 187
 188        strbuf_reset(&buf);
 189        if (read_one(state_dir_path("quiet", opts), &buf))
 190                return -1;
 191        if (buf.len)
 192                opts->flags &= ~REBASE_NO_QUIET;
 193        else
 194                opts->flags |= REBASE_NO_QUIET;
 195
 196        if (file_exists(state_dir_path("verbose", opts)))
 197                opts->flags |= REBASE_VERBOSE;
 198
 199        if (file_exists(state_dir_path("signoff", opts))) {
 200                opts->signoff = 1;
 201                opts->flags |= REBASE_FORCE;
 202        }
 203
 204        if (file_exists(state_dir_path("allow_rerere_autoupdate", opts))) {
 205                strbuf_reset(&buf);
 206                if (read_one(state_dir_path("allow_rerere_autoupdate", opts),
 207                            &buf))
 208                        return -1;
 209                if (!strcmp(buf.buf, "--rerere-autoupdate"))
 210                        opts->allow_rerere_autoupdate = 1;
 211                else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
 212                        opts->allow_rerere_autoupdate = 0;
 213                else
 214                        warning(_("ignoring invalid allow_rerere_autoupdate: "
 215                                  "'%s'"), buf.buf);
 216        } else
 217                opts->allow_rerere_autoupdate = -1;
 218
 219        if (file_exists(state_dir_path("gpg_sign_opt", opts))) {
 220                strbuf_reset(&buf);
 221                if (read_one(state_dir_path("gpg_sign_opt", opts),
 222                            &buf))
 223                        return -1;
 224                free(opts->gpg_sign_opt);
 225                opts->gpg_sign_opt = xstrdup(buf.buf);
 226        }
 227
 228        if (file_exists(state_dir_path("strategy", opts))) {
 229                strbuf_reset(&buf);
 230                if (read_one(state_dir_path("strategy", opts), &buf))
 231                        return -1;
 232                free(opts->strategy);
 233                opts->strategy = xstrdup(buf.buf);
 234        }
 235
 236        if (file_exists(state_dir_path("strategy_opts", opts))) {
 237                strbuf_reset(&buf);
 238                if (read_one(state_dir_path("strategy_opts", opts), &buf))
 239                        return -1;
 240                free(opts->strategy_opts);
 241                opts->strategy_opts = xstrdup(buf.buf);
 242        }
 243
 244        strbuf_release(&buf);
 245
 246        return 0;
 247}
 248
 249static int apply_autostash(struct rebase_options *opts)
 250{
 251        const char *path = state_dir_path("autostash", opts);
 252        struct strbuf autostash = STRBUF_INIT;
 253        struct child_process stash_apply = CHILD_PROCESS_INIT;
 254
 255        if (!file_exists(path))
 256                return 0;
 257
 258        if (read_one(path, &autostash))
 259                return error(_("Could not read '%s'"), path);
 260        /* Ensure that the hash is not mistaken for a number */
 261        strbuf_addstr(&autostash, "^0");
 262        argv_array_pushl(&stash_apply.args,
 263                         "stash", "apply", autostash.buf, NULL);
 264        stash_apply.git_cmd = 1;
 265        stash_apply.no_stderr = stash_apply.no_stdout =
 266                stash_apply.no_stdin = 1;
 267        if (!run_command(&stash_apply))
 268                printf(_("Applied autostash.\n"));
 269        else {
 270                struct argv_array args = ARGV_ARRAY_INIT;
 271                int res = 0;
 272
 273                argv_array_pushl(&args,
 274                                 "stash", "store", "-m", "autostash", "-q",
 275                                 autostash.buf, NULL);
 276                if (run_command_v_opt(args.argv, RUN_GIT_CMD))
 277                        res = error(_("Cannot store %s"), autostash.buf);
 278                argv_array_clear(&args);
 279                strbuf_release(&autostash);
 280                if (res)
 281                        return res;
 282
 283                fprintf(stderr,
 284                        _("Applying autostash resulted in conflicts.\n"
 285                          "Your changes are safe in the stash.\n"
 286                          "You can run \"git stash pop\" or \"git stash drop\" "
 287                          "at any time.\n"));
 288        }
 289
 290        strbuf_release(&autostash);
 291        return 0;
 292}
 293
 294static int finish_rebase(struct rebase_options *opts)
 295{
 296        struct strbuf dir = STRBUF_INIT;
 297        const char *argv_gc_auto[] = { "gc", "--auto", NULL };
 298
 299        delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
 300        apply_autostash(opts);
 301        close_all_packs(the_repository->objects);
 302        /*
 303         * We ignore errors in 'gc --auto', since the
 304         * user should see them.
 305         */
 306        run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
 307        strbuf_addstr(&dir, opts->state_dir);
 308        remove_dir_recursively(&dir, 0);
 309        strbuf_release(&dir);
 310
 311        return 0;
 312}
 313
 314static struct commit *peel_committish(const char *name)
 315{
 316        struct object *obj;
 317        struct object_id oid;
 318
 319        if (get_oid(name, &oid))
 320                return NULL;
 321        obj = parse_object(the_repository, &oid);
 322        return (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
 323}
 324
 325static void add_var(struct strbuf *buf, const char *name, const char *value)
 326{
 327        if (!value)
 328                strbuf_addf(buf, "unset %s; ", name);
 329        else {
 330                strbuf_addf(buf, "%s=", name);
 331                sq_quote_buf(buf, value);
 332                strbuf_addstr(buf, "; ");
 333        }
 334}
 335
 336#define GIT_REFLOG_ACTION_ENVIRONMENT "GIT_REFLOG_ACTION"
 337
 338#define RESET_HEAD_DETACH (1<<0)
 339#define RESET_HEAD_HARD (1<<1)
 340
 341static int reset_head(struct object_id *oid, const char *action,
 342                      const char *switch_to_branch, unsigned flags,
 343                      const char *reflog_orig_head, const char *reflog_head)
 344{
 345        unsigned detach_head = flags & RESET_HEAD_DETACH;
 346        unsigned reset_hard = flags & RESET_HEAD_HARD;
 347        struct object_id head_oid;
 348        struct tree_desc desc[2] = { { NULL }, { NULL } };
 349        struct lock_file lock = LOCK_INIT;
 350        struct unpack_trees_options unpack_tree_opts;
 351        struct tree *tree;
 352        const char *reflog_action;
 353        struct strbuf msg = STRBUF_INIT;
 354        size_t prefix_len;
 355        struct object_id *orig = NULL, oid_orig,
 356                *old_orig = NULL, oid_old_orig;
 357        int ret = 0, nr = 0;
 358
 359        if (switch_to_branch && !starts_with(switch_to_branch, "refs/"))
 360                BUG("Not a fully qualified branch: '%s'", switch_to_branch);
 361
 362        if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0) {
 363                ret = -1;
 364                goto leave_reset_head;
 365        }
 366
 367        if ((!oid || !reset_hard) && get_oid("HEAD", &head_oid)) {
 368                ret = error(_("could not determine HEAD revision"));
 369                goto leave_reset_head;
 370        }
 371
 372        if (!oid)
 373                oid = &head_oid;
 374
 375        memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
 376        setup_unpack_trees_porcelain(&unpack_tree_opts, action);
 377        unpack_tree_opts.head_idx = 1;
 378        unpack_tree_opts.src_index = the_repository->index;
 379        unpack_tree_opts.dst_index = the_repository->index;
 380        unpack_tree_opts.fn = reset_hard ? oneway_merge : twoway_merge;
 381        unpack_tree_opts.update = 1;
 382        unpack_tree_opts.merge = 1;
 383        if (!detach_head)
 384                unpack_tree_opts.reset = 1;
 385
 386        if (read_index_unmerged(the_repository->index) < 0) {
 387                ret = error(_("could not read index"));
 388                goto leave_reset_head;
 389        }
 390
 391        if (!reset_hard && !fill_tree_descriptor(&desc[nr++], &head_oid)) {
 392                ret = error(_("failed to find tree of %s"),
 393                            oid_to_hex(&head_oid));
 394                goto leave_reset_head;
 395        }
 396
 397        if (!fill_tree_descriptor(&desc[nr++], oid)) {
 398                ret = error(_("failed to find tree of %s"), oid_to_hex(oid));
 399                goto leave_reset_head;
 400        }
 401
 402        if (unpack_trees(nr, desc, &unpack_tree_opts)) {
 403                ret = -1;
 404                goto leave_reset_head;
 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                goto leave_reset_head;
 413        }
 414
 415        reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
 416        strbuf_addf(&msg, "%s: ", reflog_action ? reflog_action : "rebase");
 417        prefix_len = msg.len;
 418
 419        if (!get_oid("ORIG_HEAD", &oid_old_orig))
 420                old_orig = &oid_old_orig;
 421        if (!get_oid("HEAD", &oid_orig)) {
 422                orig = &oid_orig;
 423                if (!reflog_orig_head) {
 424                        strbuf_addstr(&msg, "updating ORIG_HEAD");
 425                        reflog_orig_head = msg.buf;
 426                }
 427                update_ref(reflog_orig_head, "ORIG_HEAD", orig, old_orig, 0,
 428                           UPDATE_REFS_MSG_ON_ERR);
 429        } else if (old_orig)
 430                delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
 431        if (!reflog_head) {
 432                strbuf_setlen(&msg, prefix_len);
 433                strbuf_addstr(&msg, "updating HEAD");
 434                reflog_head = msg.buf;
 435        }
 436        if (!switch_to_branch)
 437                ret = update_ref(reflog_head, "HEAD", oid, orig,
 438                                 detach_head ? REF_NO_DEREF : 0,
 439                                 UPDATE_REFS_MSG_ON_ERR);
 440        else {
 441                ret = update_ref(reflog_orig_head, switch_to_branch, oid,
 442                                 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
 443                if (!ret)
 444                        ret = create_symref("HEAD", switch_to_branch,
 445                                            reflog_head);
 446        }
 447
 448leave_reset_head:
 449        strbuf_release(&msg);
 450        rollback_lock_file(&lock);
 451        while (nr)
 452                free((void *)desc[--nr].buffer);
 453        return ret;
 454}
 455
 456static const char *resolvemsg =
 457N_("Resolve all conflicts manually, mark them as resolved with\n"
 458"\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
 459"You can instead skip this commit: run \"git rebase --skip\".\n"
 460"To abort and get back to the state before \"git rebase\", run "
 461"\"git rebase --abort\".");
 462
 463static int run_specific_rebase(struct rebase_options *opts)
 464{
 465        const char *argv[] = { NULL, NULL };
 466        struct strbuf script_snippet = STRBUF_INIT, buf = STRBUF_INIT;
 467        int status;
 468        const char *backend, *backend_func;
 469
 470        if (opts->type == REBASE_INTERACTIVE) {
 471                /* Run builtin interactive rebase */
 472                struct child_process child = CHILD_PROCESS_INIT;
 473
 474                argv_array_pushf(&child.env_array, "GIT_CHERRY_PICK_HELP=%s",
 475                                 resolvemsg);
 476                if (!(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
 477                        argv_array_push(&child.env_array, "GIT_EDITOR=:");
 478                        opts->autosquash = 0;
 479                }
 480
 481                child.git_cmd = 1;
 482                argv_array_push(&child.args, "rebase--interactive");
 483
 484                if (opts->action)
 485                        argv_array_pushf(&child.args, "--%s", opts->action);
 486                if (opts->keep_empty)
 487                        argv_array_push(&child.args, "--keep-empty");
 488                if (opts->rebase_merges)
 489                        argv_array_push(&child.args, "--rebase-merges");
 490                if (opts->rebase_cousins)
 491                        argv_array_push(&child.args, "--rebase-cousins");
 492                if (opts->autosquash)
 493                        argv_array_push(&child.args, "--autosquash");
 494                if (opts->flags & REBASE_VERBOSE)
 495                        argv_array_push(&child.args, "--verbose");
 496                if (opts->flags & REBASE_FORCE)
 497                        argv_array_push(&child.args, "--no-ff");
 498                if (opts->restrict_revision)
 499                        argv_array_pushf(&child.args,
 500                                         "--restrict-revision=^%s",
 501                                         oid_to_hex(&opts->restrict_revision->object.oid));
 502                if (opts->upstream)
 503                        argv_array_pushf(&child.args, "--upstream=%s",
 504                                         oid_to_hex(&opts->upstream->object.oid));
 505                if (opts->onto)
 506                        argv_array_pushf(&child.args, "--onto=%s",
 507                                         oid_to_hex(&opts->onto->object.oid));
 508                if (opts->squash_onto)
 509                        argv_array_pushf(&child.args, "--squash-onto=%s",
 510                                         oid_to_hex(opts->squash_onto));
 511                if (opts->onto_name)
 512                        argv_array_pushf(&child.args, "--onto-name=%s",
 513                                         opts->onto_name);
 514                argv_array_pushf(&child.args, "--head-name=%s",
 515                                 opts->head_name ?
 516                                 opts->head_name : "detached HEAD");
 517                if (opts->strategy)
 518                        argv_array_pushf(&child.args, "--strategy=%s",
 519                                         opts->strategy);
 520                if (opts->strategy_opts)
 521                        argv_array_pushf(&child.args, "--strategy-opts=%s",
 522                                         opts->strategy_opts);
 523                if (opts->switch_to)
 524                        argv_array_pushf(&child.args, "--switch-to=%s",
 525                                         opts->switch_to);
 526                if (opts->cmd)
 527                        argv_array_pushf(&child.args, "--cmd=%s", opts->cmd);
 528                if (opts->allow_empty_message)
 529                        argv_array_push(&child.args, "--allow-empty-message");
 530                if (opts->allow_rerere_autoupdate > 0)
 531                        argv_array_push(&child.args, "--rerere-autoupdate");
 532                else if (opts->allow_rerere_autoupdate == 0)
 533                        argv_array_push(&child.args, "--no-rerere-autoupdate");
 534                if (opts->gpg_sign_opt)
 535                        argv_array_push(&child.args, opts->gpg_sign_opt);
 536                if (opts->signoff)
 537                        argv_array_push(&child.args, "--signoff");
 538
 539                status = run_command(&child);
 540                goto finished_rebase;
 541        }
 542
 543        add_var(&script_snippet, "GIT_DIR", absolute_path(get_git_dir()));
 544        add_var(&script_snippet, "state_dir", opts->state_dir);
 545
 546        add_var(&script_snippet, "upstream_name", opts->upstream_name);
 547        add_var(&script_snippet, "upstream", opts->upstream ?
 548                oid_to_hex(&opts->upstream->object.oid) : NULL);
 549        add_var(&script_snippet, "head_name",
 550                opts->head_name ? opts->head_name : "detached HEAD");
 551        add_var(&script_snippet, "orig_head", oid_to_hex(&opts->orig_head));
 552        add_var(&script_snippet, "onto", opts->onto ?
 553                oid_to_hex(&opts->onto->object.oid) : NULL);
 554        add_var(&script_snippet, "onto_name", opts->onto_name);
 555        add_var(&script_snippet, "revisions", opts->revisions);
 556        add_var(&script_snippet, "restrict_revision", opts->restrict_revision ?
 557                oid_to_hex(&opts->restrict_revision->object.oid) : NULL);
 558        add_var(&script_snippet, "GIT_QUIET",
 559                opts->flags & REBASE_NO_QUIET ? "" : "t");
 560        sq_quote_argv_pretty(&buf, opts->git_am_opts.argv);
 561        add_var(&script_snippet, "git_am_opt", buf.buf);
 562        strbuf_release(&buf);
 563        add_var(&script_snippet, "verbose",
 564                opts->flags & REBASE_VERBOSE ? "t" : "");
 565        add_var(&script_snippet, "diffstat",
 566                opts->flags & REBASE_DIFFSTAT ? "t" : "");
 567        add_var(&script_snippet, "force_rebase",
 568                opts->flags & REBASE_FORCE ? "t" : "");
 569        if (opts->switch_to)
 570                add_var(&script_snippet, "switch_to", opts->switch_to);
 571        add_var(&script_snippet, "action", opts->action ? opts->action : "");
 572        add_var(&script_snippet, "signoff", opts->signoff ? "--signoff" : "");
 573        add_var(&script_snippet, "allow_rerere_autoupdate",
 574                opts->allow_rerere_autoupdate < 0 ? "" :
 575                opts->allow_rerere_autoupdate ?
 576                "--rerere-autoupdate" : "--no-rerere-autoupdate");
 577        add_var(&script_snippet, "keep_empty", opts->keep_empty ? "yes" : "");
 578        add_var(&script_snippet, "autosquash", opts->autosquash ? "t" : "");
 579        add_var(&script_snippet, "gpg_sign_opt", opts->gpg_sign_opt);
 580        add_var(&script_snippet, "cmd", opts->cmd);
 581        add_var(&script_snippet, "allow_empty_message",
 582                opts->allow_empty_message ?  "--allow-empty-message" : "");
 583        add_var(&script_snippet, "rebase_merges",
 584                opts->rebase_merges ? "t" : "");
 585        add_var(&script_snippet, "rebase_cousins",
 586                opts->rebase_cousins ? "t" : "");
 587        add_var(&script_snippet, "strategy", opts->strategy);
 588        add_var(&script_snippet, "strategy_opts", opts->strategy_opts);
 589        add_var(&script_snippet, "rebase_root", opts->root ? "t" : "");
 590        add_var(&script_snippet, "squash_onto",
 591                opts->squash_onto ? oid_to_hex(opts->squash_onto) : "");
 592        add_var(&script_snippet, "git_format_patch_opt",
 593                opts->git_format_patch_opt.buf);
 594
 595        if (is_interactive(opts) &&
 596            !(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
 597                strbuf_addstr(&script_snippet,
 598                              "GIT_EDITOR=:; export GIT_EDITOR; ");
 599                opts->autosquash = 0;
 600        }
 601
 602        switch (opts->type) {
 603        case REBASE_AM:
 604                backend = "git-rebase--am";
 605                backend_func = "git_rebase__am";
 606                break;
 607        case REBASE_MERGE:
 608                backend = "git-rebase--merge";
 609                backend_func = "git_rebase__merge";
 610                break;
 611        case REBASE_PRESERVE_MERGES:
 612                backend = "git-rebase--preserve-merges";
 613                backend_func = "git_rebase__preserve_merges";
 614                break;
 615        default:
 616                BUG("Unhandled rebase type %d", opts->type);
 617                break;
 618        }
 619
 620        strbuf_addf(&script_snippet,
 621                    ". git-sh-setup && . git-rebase--common &&"
 622                    " . %s && %s", backend, backend_func);
 623        argv[0] = script_snippet.buf;
 624
 625        status = run_command_v_opt(argv, RUN_USING_SHELL);
 626finished_rebase:
 627        if (opts->dont_finish_rebase)
 628                ; /* do nothing */
 629        else if (opts->type == REBASE_INTERACTIVE)
 630                ; /* interactive rebase cleans up after itself */
 631        else if (status == 0) {
 632                if (!file_exists(state_dir_path("stopped-sha", opts)))
 633                        finish_rebase(opts);
 634        } else if (status == 2) {
 635                struct strbuf dir = STRBUF_INIT;
 636
 637                apply_autostash(opts);
 638                strbuf_addstr(&dir, opts->state_dir);
 639                remove_dir_recursively(&dir, 0);
 640                strbuf_release(&dir);
 641                die("Nothing to do");
 642        }
 643
 644        strbuf_release(&script_snippet);
 645
 646        return status ? -1 : 0;
 647}
 648
 649static int rebase_config(const char *var, const char *value, void *data)
 650{
 651        struct rebase_options *opts = data;
 652
 653        if (!strcmp(var, "rebase.stat")) {
 654                if (git_config_bool(var, value))
 655                        opts->flags |= REBASE_DIFFSTAT;
 656                else
 657                        opts->flags &= !REBASE_DIFFSTAT;
 658                return 0;
 659        }
 660
 661        if (!strcmp(var, "rebase.autosquash")) {
 662                opts->autosquash = git_config_bool(var, value);
 663                return 0;
 664        }
 665
 666        if (!strcmp(var, "commit.gpgsign")) {
 667                free(opts->gpg_sign_opt);
 668                opts->gpg_sign_opt = git_config_bool(var, value) ?
 669                        xstrdup("-S") : NULL;
 670                return 0;
 671        }
 672
 673        if (!strcmp(var, "rebase.autostash")) {
 674                opts->autostash = git_config_bool(var, value);
 675                return 0;
 676        }
 677
 678        return git_default_config(var, value, data);
 679}
 680
 681/*
 682 * Determines whether the commits in from..to are linear, i.e. contain
 683 * no merge commits. This function *expects* `from` to be an ancestor of
 684 * `to`.
 685 */
 686static int is_linear_history(struct commit *from, struct commit *to)
 687{
 688        while (to && to != from) {
 689                parse_commit(to);
 690                if (!to->parents)
 691                        return 1;
 692                if (to->parents->next)
 693                        return 0;
 694                to = to->parents->item;
 695        }
 696        return 1;
 697}
 698
 699static int can_fast_forward(struct commit *onto, struct object_id *head_oid,
 700                            struct object_id *merge_base)
 701{
 702        struct commit *head = lookup_commit(the_repository, head_oid);
 703        struct commit_list *merge_bases;
 704        int res;
 705
 706        if (!head)
 707                return 0;
 708
 709        merge_bases = get_merge_bases(onto, head);
 710        if (merge_bases && !merge_bases->next) {
 711                oidcpy(merge_base, &merge_bases->item->object.oid);
 712                res = oideq(merge_base, &onto->object.oid);
 713        } else {
 714                oidcpy(merge_base, &null_oid);
 715                res = 0;
 716        }
 717        free_commit_list(merge_bases);
 718        return res && is_linear_history(onto, head);
 719}
 720
 721/* -i followed by -m is still -i */
 722static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
 723{
 724        struct rebase_options *opts = opt->value;
 725
 726        BUG_ON_OPT_NEG(unset);
 727        BUG_ON_OPT_ARG(arg);
 728
 729        if (!is_interactive(opts))
 730                opts->type = REBASE_MERGE;
 731
 732        return 0;
 733}
 734
 735/* -i followed by -p is still explicitly interactive, but -p alone is not */
 736static int parse_opt_interactive(const struct option *opt, const char *arg,
 737                                 int unset)
 738{
 739        struct rebase_options *opts = opt->value;
 740
 741        BUG_ON_OPT_NEG(unset);
 742        BUG_ON_OPT_ARG(arg);
 743
 744        opts->type = REBASE_INTERACTIVE;
 745        opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
 746
 747        return 0;
 748}
 749
 750static void NORETURN error_on_missing_default_upstream(void)
 751{
 752        struct branch *current_branch = branch_get(NULL);
 753
 754        printf(_("%s\n"
 755                 "Please specify which branch you want to rebase against.\n"
 756                 "See git-rebase(1) for details.\n"
 757                 "\n"
 758                 "    git rebase '<branch>'\n"
 759                 "\n"),
 760                current_branch ? _("There is no tracking information for "
 761                        "the current branch.") :
 762                        _("You are not currently on a branch."));
 763
 764        if (current_branch) {
 765                const char *remote = current_branch->remote_name;
 766
 767                if (!remote)
 768                        remote = _("<remote>");
 769
 770                printf(_("If you wish to set tracking information for this "
 771                         "branch you can do so with:\n"
 772                         "\n"
 773                         "    git branch --set-upstream-to=%s/<branch> %s\n"
 774                         "\n"),
 775                       remote, current_branch->name);
 776        }
 777        exit(1);
 778}
 779
 780static void set_reflog_action(struct rebase_options *options)
 781{
 782        const char *env;
 783        struct strbuf buf = STRBUF_INIT;
 784
 785        if (!is_interactive(options))
 786                return;
 787
 788        env = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
 789        if (env && strcmp("rebase", env))
 790                return; /* only override it if it is "rebase" */
 791
 792        strbuf_addf(&buf, "rebase -i (%s)", options->action);
 793        setenv(GIT_REFLOG_ACTION_ENVIRONMENT, buf.buf, 1);
 794        strbuf_release(&buf);
 795}
 796
 797int cmd_rebase(int argc, const char **argv, const char *prefix)
 798{
 799        struct rebase_options options = {
 800                .type = REBASE_UNSPECIFIED,
 801                .flags = REBASE_NO_QUIET,
 802                .git_am_opts = ARGV_ARRAY_INIT,
 803                .allow_rerere_autoupdate  = -1,
 804                .allow_empty_message = 1,
 805                .git_format_patch_opt = STRBUF_INIT,
 806        };
 807        const char *branch_name;
 808        int ret, flags, total_argc, in_progress = 0;
 809        int ok_to_skip_pre_rebase = 0;
 810        struct strbuf msg = STRBUF_INIT;
 811        struct strbuf revisions = STRBUF_INIT;
 812        struct strbuf buf = STRBUF_INIT;
 813        struct object_id merge_base;
 814        enum {
 815                NO_ACTION,
 816                ACTION_CONTINUE,
 817                ACTION_SKIP,
 818                ACTION_ABORT,
 819                ACTION_QUIT,
 820                ACTION_EDIT_TODO,
 821                ACTION_SHOW_CURRENT_PATCH,
 822        } action = NO_ACTION;
 823        const char *gpg_sign = NULL;
 824        struct string_list exec = STRING_LIST_INIT_NODUP;
 825        const char *rebase_merges = NULL;
 826        int fork_point = -1;
 827        struct string_list strategy_options = STRING_LIST_INIT_NODUP;
 828        struct object_id squash_onto;
 829        char *squash_onto_name = NULL;
 830        struct option builtin_rebase_options[] = {
 831                OPT_STRING(0, "onto", &options.onto_name,
 832                           N_("revision"),
 833                           N_("rebase onto given branch instead of upstream")),
 834                OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
 835                         N_("allow pre-rebase hook to run")),
 836                OPT_NEGBIT('q', "quiet", &options.flags,
 837                           N_("be quiet. implies --no-stat"),
 838                           REBASE_NO_QUIET| REBASE_VERBOSE | REBASE_DIFFSTAT),
 839                OPT_BIT('v', "verbose", &options.flags,
 840                        N_("display a diffstat of what changed upstream"),
 841                        REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
 842                {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
 843                        N_("do not show diffstat of what changed upstream"),
 844                        PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
 845                OPT_BOOL(0, "signoff", &options.signoff,
 846                         N_("add a Signed-off-by: line to each commit")),
 847                OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &options.git_am_opts,
 848                                  NULL, N_("passed to 'git am'"),
 849                                  PARSE_OPT_NOARG),
 850                OPT_PASSTHRU_ARGV(0, "committer-date-is-author-date",
 851                                  &options.git_am_opts, NULL,
 852                                  N_("passed to 'git am'"), PARSE_OPT_NOARG),
 853                OPT_PASSTHRU_ARGV(0, "ignore-date", &options.git_am_opts, NULL,
 854                                  N_("passed to 'git am'"), PARSE_OPT_NOARG),
 855                OPT_PASSTHRU_ARGV('C', NULL, &options.git_am_opts, N_("n"),
 856                                  N_("passed to 'git apply'"), 0),
 857                OPT_PASSTHRU_ARGV(0, "whitespace", &options.git_am_opts,
 858                                  N_("action"), N_("passed to 'git apply'"), 0),
 859                OPT_BIT('f', "force-rebase", &options.flags,
 860                        N_("cherry-pick all commits, even if unchanged"),
 861                        REBASE_FORCE),
 862                OPT_BIT(0, "no-ff", &options.flags,
 863                        N_("cherry-pick all commits, even if unchanged"),
 864                        REBASE_FORCE),
 865                OPT_CMDMODE(0, "continue", &action, N_("continue"),
 866                            ACTION_CONTINUE),
 867                OPT_CMDMODE(0, "skip", &action,
 868                            N_("skip current patch and continue"), ACTION_SKIP),
 869                OPT_CMDMODE(0, "abort", &action,
 870                            N_("abort and check out the original branch"),
 871                            ACTION_ABORT),
 872                OPT_CMDMODE(0, "quit", &action,
 873                            N_("abort but keep HEAD where it is"), ACTION_QUIT),
 874                OPT_CMDMODE(0, "edit-todo", &action, N_("edit the todo list "
 875                            "during an interactive rebase"), ACTION_EDIT_TODO),
 876                OPT_CMDMODE(0, "show-current-patch", &action,
 877                            N_("show the patch file being applied or merged"),
 878                            ACTION_SHOW_CURRENT_PATCH),
 879                { OPTION_CALLBACK, 'm', "merge", &options, NULL,
 880                        N_("use merging strategies to rebase"),
 881                        PARSE_OPT_NOARG | PARSE_OPT_NONEG,
 882                        parse_opt_merge },
 883                { OPTION_CALLBACK, 'i', "interactive", &options, NULL,
 884                        N_("let the user edit the list of commits to rebase"),
 885                        PARSE_OPT_NOARG | PARSE_OPT_NONEG,
 886                        parse_opt_interactive },
 887                OPT_SET_INT('p', "preserve-merges", &options.type,
 888                            N_("try to recreate merges instead of ignoring "
 889                               "them"), REBASE_PRESERVE_MERGES),
 890                OPT_BOOL(0, "rerere-autoupdate",
 891                         &options.allow_rerere_autoupdate,
 892                         N_("allow rerere to update index with resolved "
 893                            "conflict")),
 894                OPT_BOOL('k', "keep-empty", &options.keep_empty,
 895                         N_("preserve empty commits during rebase")),
 896                OPT_BOOL(0, "autosquash", &options.autosquash,
 897                         N_("move commits that begin with "
 898                            "squash!/fixup! under -i")),
 899                { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
 900                        N_("GPG-sign commits"),
 901                        PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
 902                OPT_BOOL(0, "autostash", &options.autostash,
 903                         N_("automatically stash/stash pop before and after")),
 904                OPT_STRING_LIST('x', "exec", &exec, N_("exec"),
 905                                N_("add exec lines after each commit of the "
 906                                   "editable list")),
 907                OPT_BOOL(0, "allow-empty-message",
 908                         &options.allow_empty_message,
 909                         N_("allow rebasing commits with empty messages")),
 910                {OPTION_STRING, 'r', "rebase-merges", &rebase_merges,
 911                        N_("mode"),
 912                        N_("try to rebase merges instead of skipping them"),
 913                        PARSE_OPT_OPTARG, NULL, (intptr_t)""},
 914                OPT_BOOL(0, "fork-point", &fork_point,
 915                         N_("use 'merge-base --fork-point' to refine upstream")),
 916                OPT_STRING('s', "strategy", &options.strategy,
 917                           N_("strategy"), N_("use the given merge strategy")),
 918                OPT_STRING_LIST('X', "strategy-option", &strategy_options,
 919                                N_("option"),
 920                                N_("pass the argument through to the merge "
 921                                   "strategy")),
 922                OPT_BOOL(0, "root", &options.root,
 923                         N_("rebase all reachable commits up to the root(s)")),
 924                OPT_END(),
 925        };
 926        int i;
 927
 928        /*
 929         * NEEDSWORK: Once the builtin rebase has been tested enough
 930         * and git-legacy-rebase.sh is retired to contrib/, this preamble
 931         * can be removed.
 932         */
 933
 934        if (!use_builtin_rebase()) {
 935                const char *path = mkpath("%s/git-legacy-rebase",
 936                                          git_exec_path());
 937
 938                if (sane_execvp(path, (char **)argv) < 0)
 939                        die_errno(_("could not exec %s"), path);
 940                else
 941                        BUG("sane_execvp() returned???");
 942        }
 943
 944        if (argc == 2 && !strcmp(argv[1], "-h"))
 945                usage_with_options(builtin_rebase_usage,
 946                                   builtin_rebase_options);
 947
 948        prefix = setup_git_directory();
 949        trace_repo_setup(prefix);
 950        setup_work_tree();
 951
 952        git_config(rebase_config, &options);
 953
 954        strbuf_reset(&buf);
 955        strbuf_addf(&buf, "%s/applying", apply_dir());
 956        if(file_exists(buf.buf))
 957                die(_("It looks like 'git am' is in progress. Cannot rebase."));
 958
 959        if (is_directory(apply_dir())) {
 960                options.type = REBASE_AM;
 961                options.state_dir = apply_dir();
 962        } else if (is_directory(merge_dir())) {
 963                strbuf_reset(&buf);
 964                strbuf_addf(&buf, "%s/rewritten", merge_dir());
 965                if (is_directory(buf.buf)) {
 966                        options.type = REBASE_PRESERVE_MERGES;
 967                        options.flags |= REBASE_INTERACTIVE_EXPLICIT;
 968                } else {
 969                        strbuf_reset(&buf);
 970                        strbuf_addf(&buf, "%s/interactive", merge_dir());
 971                        if(file_exists(buf.buf)) {
 972                                options.type = REBASE_INTERACTIVE;
 973                                options.flags |= REBASE_INTERACTIVE_EXPLICIT;
 974                        } else
 975                                options.type = REBASE_MERGE;
 976                }
 977                options.state_dir = merge_dir();
 978        }
 979
 980        if (options.type != REBASE_UNSPECIFIED)
 981                in_progress = 1;
 982
 983        total_argc = argc;
 984        argc = parse_options(argc, argv, prefix,
 985                             builtin_rebase_options,
 986                             builtin_rebase_usage, 0);
 987
 988        if (action != NO_ACTION && total_argc != 2) {
 989                usage_with_options(builtin_rebase_usage,
 990                                   builtin_rebase_options);
 991        }
 992
 993        if (argc > 2)
 994                usage_with_options(builtin_rebase_usage,
 995                                   builtin_rebase_options);
 996
 997        if (action != NO_ACTION && !in_progress)
 998                die(_("No rebase in progress?"));
 999        setenv(GIT_REFLOG_ACTION_ENVIRONMENT, "rebase", 0);
1000
1001        if (action == ACTION_EDIT_TODO && !is_interactive(&options))
1002                die(_("The --edit-todo action can only be used during "
1003                      "interactive rebase."));
1004
1005        switch (action) {
1006        case ACTION_CONTINUE: {
1007                struct object_id head;
1008                struct lock_file lock_file = LOCK_INIT;
1009                int fd;
1010
1011                options.action = "continue";
1012                set_reflog_action(&options);
1013
1014                /* Sanity check */
1015                if (get_oid("HEAD", &head))
1016                        die(_("Cannot read HEAD"));
1017
1018                fd = hold_locked_index(&lock_file, 0);
1019                if (read_index(the_repository->index) < 0)
1020                        die(_("could not read index"));
1021                refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
1022                              NULL);
1023                if (0 <= fd)
1024                        update_index_if_able(the_repository->index,
1025                                             &lock_file);
1026                rollback_lock_file(&lock_file);
1027
1028                if (has_unstaged_changes(1)) {
1029                        puts(_("You must edit all merge conflicts and then\n"
1030                               "mark them as resolved using git add"));
1031                        exit(1);
1032                }
1033                if (read_basic_state(&options))
1034                        exit(1);
1035                goto run_rebase;
1036        }
1037        case ACTION_SKIP: {
1038                struct string_list merge_rr = STRING_LIST_INIT_DUP;
1039
1040                options.action = "skip";
1041                set_reflog_action(&options);
1042
1043                rerere_clear(&merge_rr);
1044                string_list_clear(&merge_rr, 1);
1045
1046                if (reset_head(NULL, "reset", NULL, RESET_HEAD_HARD,
1047                               NULL, NULL) < 0)
1048                        die(_("could not discard worktree changes"));
1049                remove_branch_state();
1050                if (read_basic_state(&options))
1051                        exit(1);
1052                goto run_rebase;
1053        }
1054        case ACTION_ABORT: {
1055                struct string_list merge_rr = STRING_LIST_INIT_DUP;
1056                options.action = "abort";
1057                set_reflog_action(&options);
1058
1059                rerere_clear(&merge_rr);
1060                string_list_clear(&merge_rr, 1);
1061
1062                if (read_basic_state(&options))
1063                        exit(1);
1064                if (reset_head(&options.orig_head, "reset",
1065                               options.head_name, RESET_HEAD_HARD,
1066                               NULL, NULL) < 0)
1067                        die(_("could not move back to %s"),
1068                            oid_to_hex(&options.orig_head));
1069                remove_branch_state();
1070                ret = finish_rebase(&options);
1071                goto cleanup;
1072        }
1073        case ACTION_QUIT: {
1074                strbuf_reset(&buf);
1075                strbuf_addstr(&buf, options.state_dir);
1076                ret = !!remove_dir_recursively(&buf, 0);
1077                if (ret)
1078                        die(_("could not remove '%s'"), options.state_dir);
1079                goto cleanup;
1080        }
1081        case ACTION_EDIT_TODO:
1082                options.action = "edit-todo";
1083                options.dont_finish_rebase = 1;
1084                goto run_rebase;
1085        case ACTION_SHOW_CURRENT_PATCH:
1086                options.action = "show-current-patch";
1087                options.dont_finish_rebase = 1;
1088                goto run_rebase;
1089        case NO_ACTION:
1090                break;
1091        default:
1092                BUG("action: %d", action);
1093        }
1094
1095        /* Make sure no rebase is in progress */
1096        if (in_progress) {
1097                const char *last_slash = strrchr(options.state_dir, '/');
1098                const char *state_dir_base =
1099                        last_slash ? last_slash + 1 : options.state_dir;
1100                const char *cmd_live_rebase =
1101                        "git rebase (--continue | --abort | --skip)";
1102                strbuf_reset(&buf);
1103                strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
1104                die(_("It seems that there is already a %s directory, and\n"
1105                      "I wonder if you are in the middle of another rebase.  "
1106                      "If that is the\n"
1107                      "case, please try\n\t%s\n"
1108                      "If that is not the case, please\n\t%s\n"
1109                      "and run me again.  I am stopping in case you still "
1110                      "have something\n"
1111                      "valuable there.\n"),
1112                    state_dir_base, cmd_live_rebase, buf.buf);
1113        }
1114
1115        for (i = 0; i < options.git_am_opts.argc; i++) {
1116                const char *option = options.git_am_opts.argv[i], *p;
1117                if (!strcmp(option, "--committer-date-is-author-date") ||
1118                    !strcmp(option, "--ignore-date") ||
1119                    !strcmp(option, "--whitespace=fix") ||
1120                    !strcmp(option, "--whitespace=strip"))
1121                        options.flags |= REBASE_FORCE;
1122                else if (skip_prefix(option, "-C", &p)) {
1123                        while (*p)
1124                                if (!isdigit(*(p++)))
1125                                        die(_("switch `C' expects a "
1126                                              "numerical value"));
1127                } else if (skip_prefix(option, "--whitespace=", &p)) {
1128                        if (*p && strcmp(p, "warn") && strcmp(p, "nowarn") &&
1129                            strcmp(p, "error") && strcmp(p, "error-all"))
1130                                die("Invalid whitespace option: '%s'", p);
1131                }
1132        }
1133
1134        if (!(options.flags & REBASE_NO_QUIET))
1135                argv_array_push(&options.git_am_opts, "-q");
1136
1137        if (options.keep_empty)
1138                imply_interactive(&options, "--keep-empty");
1139
1140        if (gpg_sign) {
1141                free(options.gpg_sign_opt);
1142                options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
1143        }
1144
1145        if (exec.nr) {
1146                int i;
1147
1148                imply_interactive(&options, "--exec");
1149
1150                strbuf_reset(&buf);
1151                for (i = 0; i < exec.nr; i++)
1152                        strbuf_addf(&buf, "exec %s\n", exec.items[i].string);
1153                options.cmd = xstrdup(buf.buf);
1154        }
1155
1156        if (rebase_merges) {
1157                if (!*rebase_merges)
1158                        ; /* default mode; do nothing */
1159                else if (!strcmp("rebase-cousins", rebase_merges))
1160                        options.rebase_cousins = 1;
1161                else if (strcmp("no-rebase-cousins", rebase_merges))
1162                        die(_("Unknown mode: %s"), rebase_merges);
1163                options.rebase_merges = 1;
1164                imply_interactive(&options, "--rebase-merges");
1165        }
1166
1167        if (strategy_options.nr) {
1168                int i;
1169
1170                if (!options.strategy)
1171                        options.strategy = "recursive";
1172
1173                strbuf_reset(&buf);
1174                for (i = 0; i < strategy_options.nr; i++)
1175                        strbuf_addf(&buf, " --%s",
1176                                    strategy_options.items[i].string);
1177                options.strategy_opts = xstrdup(buf.buf);
1178        }
1179
1180        if (options.strategy) {
1181                options.strategy = xstrdup(options.strategy);
1182                switch (options.type) {
1183                case REBASE_AM:
1184                        die(_("--strategy requires --merge or --interactive"));
1185                case REBASE_MERGE:
1186                case REBASE_INTERACTIVE:
1187                case REBASE_PRESERVE_MERGES:
1188                        /* compatible */
1189                        break;
1190                case REBASE_UNSPECIFIED:
1191                        options.type = REBASE_MERGE;
1192                        break;
1193                default:
1194                        BUG("unhandled rebase type (%d)", options.type);
1195                }
1196        }
1197
1198        if (options.root && !options.onto_name)
1199                imply_interactive(&options, "--root without --onto");
1200
1201        if (isatty(2) && options.flags & REBASE_NO_QUIET)
1202                strbuf_addstr(&options.git_format_patch_opt, " --progress");
1203
1204        switch (options.type) {
1205        case REBASE_MERGE:
1206        case REBASE_INTERACTIVE:
1207        case REBASE_PRESERVE_MERGES:
1208                options.state_dir = merge_dir();
1209                break;
1210        case REBASE_AM:
1211                options.state_dir = apply_dir();
1212                break;
1213        default:
1214                /* the default rebase backend is `--am` */
1215                options.type = REBASE_AM;
1216                options.state_dir = apply_dir();
1217                break;
1218        }
1219
1220        if (options.git_am_opts.argc) {
1221                /* all am options except -q are compatible only with --am */
1222                for (i = options.git_am_opts.argc - 1; i >= 0; i--)
1223                        if (strcmp(options.git_am_opts.argv[i], "-q"))
1224                                break;
1225
1226                if (is_interactive(&options) && i >= 0)
1227                        die(_("error: cannot combine interactive options "
1228                              "(--interactive, --exec, --rebase-merges, "
1229                              "--preserve-merges, --keep-empty, --root + "
1230                              "--onto) with am options (%s)"), buf.buf);
1231                if (options.type == REBASE_MERGE && i >= 0)
1232                        die(_("error: cannot combine merge options (--merge, "
1233                              "--strategy, --strategy-option) with am options "
1234                              "(%s)"), buf.buf);
1235        }
1236
1237        if (options.signoff) {
1238                if (options.type == REBASE_PRESERVE_MERGES)
1239                        die("cannot combine '--signoff' with "
1240                            "'--preserve-merges'");
1241                argv_array_push(&options.git_am_opts, "--signoff");
1242                options.flags |= REBASE_FORCE;
1243        }
1244
1245        if (options.type == REBASE_PRESERVE_MERGES)
1246                /*
1247                 * Note: incompatibility with --signoff handled in signoff block above
1248                 * Note: incompatibility with --interactive is just a strong warning;
1249                 *       git-rebase.txt caveats with "unless you know what you are doing"
1250                 */
1251                if (options.rebase_merges)
1252                        die(_("error: cannot combine '--preserve-merges' with "
1253                              "'--rebase-merges'"));
1254
1255        if (options.rebase_merges) {
1256                if (strategy_options.nr)
1257                        die(_("error: cannot combine '--rebase-merges' with "
1258                              "'--strategy-option'"));
1259                if (options.strategy)
1260                        die(_("error: cannot combine '--rebase-merges' with "
1261                              "'--strategy'"));
1262        }
1263
1264        if (!options.root) {
1265                if (argc < 1) {
1266                        struct branch *branch;
1267
1268                        branch = branch_get(NULL);
1269                        options.upstream_name = branch_get_upstream(branch,
1270                                                                    NULL);
1271                        if (!options.upstream_name)
1272                                error_on_missing_default_upstream();
1273                        if (fork_point < 0)
1274                                fork_point = 1;
1275                } else {
1276                        options.upstream_name = argv[0];
1277                        argc--;
1278                        argv++;
1279                        if (!strcmp(options.upstream_name, "-"))
1280                                options.upstream_name = "@{-1}";
1281                }
1282                options.upstream = peel_committish(options.upstream_name);
1283                if (!options.upstream)
1284                        die(_("invalid upstream '%s'"), options.upstream_name);
1285                options.upstream_arg = options.upstream_name;
1286        } else {
1287                if (!options.onto_name) {
1288                        if (commit_tree("", 0, the_hash_algo->empty_tree, NULL,
1289                                        &squash_onto, NULL, NULL) < 0)
1290                                die(_("Could not create new root commit"));
1291                        options.squash_onto = &squash_onto;
1292                        options.onto_name = squash_onto_name =
1293                                xstrdup(oid_to_hex(&squash_onto));
1294                }
1295                options.upstream_name = NULL;
1296                options.upstream = NULL;
1297                if (argc > 1)
1298                        usage_with_options(builtin_rebase_usage,
1299                                           builtin_rebase_options);
1300                options.upstream_arg = "--root";
1301        }
1302
1303        /* Make sure the branch to rebase onto is valid. */
1304        if (!options.onto_name)
1305                options.onto_name = options.upstream_name;
1306        if (strstr(options.onto_name, "...")) {
1307                if (get_oid_mb(options.onto_name, &merge_base) < 0)
1308                        die(_("'%s': need exactly one merge base"),
1309                            options.onto_name);
1310                options.onto = lookup_commit_or_die(&merge_base,
1311                                                    options.onto_name);
1312        } else {
1313                options.onto = peel_committish(options.onto_name);
1314                if (!options.onto)
1315                        die(_("Does not point to a valid commit '%s'"),
1316                                options.onto_name);
1317        }
1318
1319        /*
1320         * If the branch to rebase is given, that is the branch we will rebase
1321         * branch_name -- branch/commit being rebased, or
1322         *                HEAD (already detached)
1323         * orig_head -- commit object name of tip of the branch before rebasing
1324         * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
1325         */
1326        if (argc == 1) {
1327                /* Is it "rebase other branchname" or "rebase other commit"? */
1328                branch_name = argv[0];
1329                options.switch_to = argv[0];
1330
1331                /* Is it a local branch? */
1332                strbuf_reset(&buf);
1333                strbuf_addf(&buf, "refs/heads/%s", branch_name);
1334                if (!read_ref(buf.buf, &options.orig_head))
1335                        options.head_name = xstrdup(buf.buf);
1336                /* If not is it a valid ref (branch or commit)? */
1337                else if (!get_oid(branch_name, &options.orig_head))
1338                        options.head_name = NULL;
1339                else
1340                        die(_("fatal: no such branch/commit '%s'"),
1341                            branch_name);
1342        } else if (argc == 0) {
1343                /* Do not need to switch branches, we are already on it. */
1344                options.head_name =
1345                        xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
1346                                         &flags));
1347                if (!options.head_name)
1348                        die(_("No such ref: %s"), "HEAD");
1349                if (flags & REF_ISSYMREF) {
1350                        if (!skip_prefix(options.head_name,
1351                                         "refs/heads/", &branch_name))
1352                                branch_name = options.head_name;
1353
1354                } else {
1355                        free(options.head_name);
1356                        options.head_name = NULL;
1357                        branch_name = "HEAD";
1358                }
1359                if (get_oid("HEAD", &options.orig_head))
1360                        die(_("Could not resolve HEAD to a revision"));
1361        } else
1362                BUG("unexpected number of arguments left to parse");
1363
1364        if (fork_point > 0) {
1365                struct commit *head =
1366                        lookup_commit_reference(the_repository,
1367                                                &options.orig_head);
1368                options.restrict_revision =
1369                        get_fork_point(options.upstream_name, head);
1370        }
1371
1372        if (read_index(the_repository->index) < 0)
1373                die(_("could not read index"));
1374
1375        if (options.autostash) {
1376                struct lock_file lock_file = LOCK_INIT;
1377                int fd;
1378
1379                fd = hold_locked_index(&lock_file, 0);
1380                refresh_cache(REFRESH_QUIET);
1381                if (0 <= fd)
1382                        update_index_if_able(&the_index, &lock_file);
1383                rollback_lock_file(&lock_file);
1384
1385                if (has_unstaged_changes(1) || has_uncommitted_changes(1)) {
1386                        const char *autostash =
1387                                state_dir_path("autostash", &options);
1388                        struct child_process stash = CHILD_PROCESS_INIT;
1389                        struct object_id oid;
1390                        struct commit *head =
1391                                lookup_commit_reference(the_repository,
1392                                                        &options.orig_head);
1393
1394                        argv_array_pushl(&stash.args,
1395                                         "stash", "create", "autostash", NULL);
1396                        stash.git_cmd = 1;
1397                        stash.no_stdin = 1;
1398                        strbuf_reset(&buf);
1399                        if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
1400                                die(_("Cannot autostash"));
1401                        strbuf_trim_trailing_newline(&buf);
1402                        if (get_oid(buf.buf, &oid))
1403                                die(_("Unexpected stash response: '%s'"),
1404                                    buf.buf);
1405                        strbuf_reset(&buf);
1406                        strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
1407
1408                        if (safe_create_leading_directories_const(autostash))
1409                                die(_("Could not create directory for '%s'"),
1410                                    options.state_dir);
1411                        write_file(autostash, "%s", oid_to_hex(&oid));
1412                        printf(_("Created autostash: %s\n"), buf.buf);
1413                        if (reset_head(&head->object.oid, "reset --hard",
1414                                       NULL, RESET_HEAD_HARD, NULL, NULL) < 0)
1415                                die(_("could not reset --hard"));
1416                        printf(_("HEAD is now at %s"),
1417                               find_unique_abbrev(&head->object.oid,
1418                                                  DEFAULT_ABBREV));
1419                        strbuf_reset(&buf);
1420                        pp_commit_easy(CMIT_FMT_ONELINE, head, &buf);
1421                        if (buf.len > 0)
1422                                printf(" %s", buf.buf);
1423                        putchar('\n');
1424
1425                        if (discard_index(the_repository->index) < 0 ||
1426                                read_index(the_repository->index) < 0)
1427                                die(_("could not read index"));
1428                }
1429        }
1430
1431        if (require_clean_work_tree("rebase",
1432                                    _("Please commit or stash them."), 1, 1)) {
1433                ret = 1;
1434                goto cleanup;
1435        }
1436
1437        /*
1438         * Now we are rebasing commits upstream..orig_head (or with --root,
1439         * everything leading up to orig_head) on top of onto.
1440         */
1441
1442        /*
1443         * Check if we are already based on onto with linear history,
1444         * but this should be done only when upstream and onto are the same
1445         * and if this is not an interactive rebase.
1446         */
1447        if (can_fast_forward(options.onto, &options.orig_head, &merge_base) &&
1448            !is_interactive(&options) && !options.restrict_revision &&
1449            options.upstream &&
1450            !oidcmp(&options.upstream->object.oid, &options.onto->object.oid)) {
1451                int flag;
1452
1453                if (!(options.flags & REBASE_FORCE)) {
1454                        /* Lazily switch to the target branch if needed... */
1455                        if (options.switch_to) {
1456                                struct object_id oid;
1457
1458                                if (get_oid(options.switch_to, &oid) < 0) {
1459                                        ret = !!error(_("could not parse '%s'"),
1460                                                      options.switch_to);
1461                                        goto cleanup;
1462                                }
1463
1464                                strbuf_reset(&buf);
1465                                strbuf_addf(&buf, "%s: checkout %s",
1466                                            getenv(GIT_REFLOG_ACTION_ENVIRONMENT),
1467                                            options.switch_to);
1468                                if (reset_head(&oid, "checkout",
1469                                               options.head_name, 0,
1470                                               NULL, buf.buf) < 0) {
1471                                        ret = !!error(_("could not switch to "
1472                                                        "%s"),
1473                                                      options.switch_to);
1474                                        goto cleanup;
1475                                }
1476                        }
1477
1478                        if (!(options.flags & REBASE_NO_QUIET))
1479                                ; /* be quiet */
1480                        else if (!strcmp(branch_name, "HEAD") &&
1481                                 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1482                                puts(_("HEAD is up to date."));
1483                        else
1484                                printf(_("Current branch %s is up to date.\n"),
1485                                       branch_name);
1486                        ret = !!finish_rebase(&options);
1487                        goto cleanup;
1488                } else if (!(options.flags & REBASE_NO_QUIET))
1489                        ; /* be quiet */
1490                else if (!strcmp(branch_name, "HEAD") &&
1491                         resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1492                        puts(_("HEAD is up to date, rebase forced."));
1493                else
1494                        printf(_("Current branch %s is up to date, rebase "
1495                                 "forced.\n"), branch_name);
1496        }
1497
1498        /* If a hook exists, give it a chance to interrupt*/
1499        if (!ok_to_skip_pre_rebase &&
1500            run_hook_le(NULL, "pre-rebase", options.upstream_arg,
1501                        argc ? argv[0] : NULL, NULL))
1502                die(_("The pre-rebase hook refused to rebase."));
1503
1504        if (options.flags & REBASE_DIFFSTAT) {
1505                struct diff_options opts;
1506
1507                if (options.flags & REBASE_VERBOSE) {
1508                        if (is_null_oid(&merge_base))
1509                                printf(_("Changes to %s:\n"),
1510                                       oid_to_hex(&options.onto->object.oid));
1511                        else
1512                                printf(_("Changes from %s to %s:\n"),
1513                                       oid_to_hex(&merge_base),
1514                                       oid_to_hex(&options.onto->object.oid));
1515                }
1516
1517                /* We want color (if set), but no pager */
1518                diff_setup(&opts);
1519                opts.stat_width = -1; /* use full terminal width */
1520                opts.stat_graph_width = -1; /* respect statGraphWidth config */
1521                opts.output_format |=
1522                        DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1523                opts.detect_rename = DIFF_DETECT_RENAME;
1524                diff_setup_done(&opts);
1525                diff_tree_oid(is_null_oid(&merge_base) ?
1526                              the_hash_algo->empty_tree : &merge_base,
1527                              &options.onto->object.oid, "", &opts);
1528                diffcore_std(&opts);
1529                diff_flush(&opts);
1530        }
1531
1532        if (is_interactive(&options))
1533                goto run_rebase;
1534
1535        /* Detach HEAD and reset the tree */
1536        if (options.flags & REBASE_NO_QUIET)
1537                printf(_("First, rewinding head to replay your work on top of "
1538                         "it...\n"));
1539
1540        strbuf_addf(&msg, "%s: checkout %s",
1541                    getenv(GIT_REFLOG_ACTION_ENVIRONMENT), options.onto_name);
1542        if (reset_head(&options.onto->object.oid, "checkout", NULL,
1543                       RESET_HEAD_DETACH, NULL, msg.buf))
1544                die(_("Could not detach HEAD"));
1545        strbuf_release(&msg);
1546
1547        /*
1548         * If the onto is a proper descendant of the tip of the branch, then
1549         * we just fast-forwarded.
1550         */
1551        strbuf_reset(&msg);
1552        if (!oidcmp(&merge_base, &options.orig_head)) {
1553                printf(_("Fast-forwarded %s to %s.\n"),
1554                        branch_name, options.onto_name);
1555                strbuf_addf(&msg, "rebase finished: %s onto %s",
1556                        options.head_name ? options.head_name : "detached HEAD",
1557                        oid_to_hex(&options.onto->object.oid));
1558                reset_head(NULL, "Fast-forwarded", options.head_name, 0,
1559                           "HEAD", msg.buf);
1560                strbuf_release(&msg);
1561                ret = !!finish_rebase(&options);
1562                goto cleanup;
1563        }
1564
1565        strbuf_addf(&revisions, "%s..%s",
1566                    options.root ? oid_to_hex(&options.onto->object.oid) :
1567                    (options.restrict_revision ?
1568                     oid_to_hex(&options.restrict_revision->object.oid) :
1569                     oid_to_hex(&options.upstream->object.oid)),
1570                    oid_to_hex(&options.orig_head));
1571
1572        options.revisions = revisions.buf;
1573
1574run_rebase:
1575        ret = !!run_specific_rebase(&options);
1576
1577cleanup:
1578        strbuf_release(&revisions);
1579        free(options.head_name);
1580        free(options.gpg_sign_opt);
1581        free(options.cmd);
1582        free(squash_onto_name);
1583        return ret;
1584}