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