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