builtin / rebase.con commit built-in rebase: reinstate `checkout -q` behavior where appropriate (bac2a1e)
   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 strbuf git_am_opt;
  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;
 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        add_var(&script_snippet, "git_am_opt", opts->git_am_opt.buf);
 437        add_var(&script_snippet, "verbose",
 438                opts->flags & REBASE_VERBOSE ? "t" : "");
 439        add_var(&script_snippet, "diffstat",
 440                opts->flags & REBASE_DIFFSTAT ? "t" : "");
 441        add_var(&script_snippet, "force_rebase",
 442                opts->flags & REBASE_FORCE ? "t" : "");
 443        if (opts->switch_to)
 444                add_var(&script_snippet, "switch_to", opts->switch_to);
 445        add_var(&script_snippet, "action", opts->action ? opts->action : "");
 446        add_var(&script_snippet, "signoff", opts->signoff ? "--signoff" : "");
 447        add_var(&script_snippet, "allow_rerere_autoupdate",
 448                opts->allow_rerere_autoupdate < 0 ? "" :
 449                opts->allow_rerere_autoupdate ?
 450                "--rerere-autoupdate" : "--no-rerere-autoupdate");
 451        add_var(&script_snippet, "keep_empty", opts->keep_empty ? "yes" : "");
 452        add_var(&script_snippet, "autosquash", opts->autosquash ? "t" : "");
 453        add_var(&script_snippet, "gpg_sign_opt", opts->gpg_sign_opt);
 454        add_var(&script_snippet, "cmd", opts->cmd);
 455        add_var(&script_snippet, "allow_empty_message",
 456                opts->allow_empty_message ?  "--allow-empty-message" : "");
 457        add_var(&script_snippet, "rebase_merges",
 458                opts->rebase_merges ? "t" : "");
 459        add_var(&script_snippet, "rebase_cousins",
 460                opts->rebase_cousins ? "t" : "");
 461        add_var(&script_snippet, "strategy", opts->strategy);
 462        add_var(&script_snippet, "strategy_opts", opts->strategy_opts);
 463        add_var(&script_snippet, "rebase_root", opts->root ? "t" : "");
 464        add_var(&script_snippet, "squash_onto",
 465                opts->squash_onto ? oid_to_hex(opts->squash_onto) : "");
 466        add_var(&script_snippet, "git_format_patch_opt",
 467                opts->git_format_patch_opt.buf);
 468
 469        if (is_interactive(opts) &&
 470            !(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
 471                strbuf_addstr(&script_snippet,
 472                              "GIT_EDITOR=:; export GIT_EDITOR; ");
 473                opts->autosquash = 0;
 474        }
 475
 476        switch (opts->type) {
 477        case REBASE_AM:
 478                backend = "git-rebase--am";
 479                backend_func = "git_rebase__am";
 480                break;
 481        case REBASE_MERGE:
 482                backend = "git-rebase--merge";
 483                backend_func = "git_rebase__merge";
 484                break;
 485        case REBASE_PRESERVE_MERGES:
 486                backend = "git-rebase--preserve-merges";
 487                backend_func = "git_rebase__preserve_merges";
 488                break;
 489        default:
 490                BUG("Unhandled rebase type %d", opts->type);
 491                break;
 492        }
 493
 494        strbuf_addf(&script_snippet,
 495                    ". git-sh-setup && . git-rebase--common &&"
 496                    " . %s && %s", backend, backend_func);
 497        argv[0] = script_snippet.buf;
 498
 499        status = run_command_v_opt(argv, RUN_USING_SHELL);
 500finished_rebase:
 501        if (opts->dont_finish_rebase)
 502                ; /* do nothing */
 503        else if (opts->type == REBASE_INTERACTIVE)
 504                ; /* interactive rebase cleans up after itself */
 505        else if (status == 0) {
 506                if (!file_exists(state_dir_path("stopped-sha", opts)))
 507                        finish_rebase(opts);
 508        } else if (status == 2) {
 509                struct strbuf dir = STRBUF_INIT;
 510
 511                apply_autostash(opts);
 512                strbuf_addstr(&dir, opts->state_dir);
 513                remove_dir_recursively(&dir, 0);
 514                strbuf_release(&dir);
 515                die("Nothing to do");
 516        }
 517
 518        strbuf_release(&script_snippet);
 519
 520        return status ? -1 : 0;
 521}
 522
 523#define GIT_REFLOG_ACTION_ENVIRONMENT "GIT_REFLOG_ACTION"
 524
 525#define RESET_HEAD_DETACH (1<<0)
 526#define RESET_HEAD_HARD (1<<1)
 527
 528static int reset_head(struct object_id *oid, const char *action,
 529                      const char *switch_to_branch, unsigned flags,
 530                      const char *reflog_orig_head, const char *reflog_head)
 531{
 532        unsigned detach_head = flags & RESET_HEAD_DETACH;
 533        unsigned reset_hard = flags & RESET_HEAD_HARD;
 534        struct object_id head_oid;
 535        struct tree_desc desc[2] = { { NULL }, { NULL } };
 536        struct lock_file lock = LOCK_INIT;
 537        struct unpack_trees_options unpack_tree_opts;
 538        struct tree *tree;
 539        const char *reflog_action;
 540        struct strbuf msg = STRBUF_INIT;
 541        size_t prefix_len;
 542        struct object_id *orig = NULL, oid_orig,
 543                *old_orig = NULL, oid_old_orig;
 544        int ret = 0, nr = 0;
 545
 546        if (switch_to_branch && !starts_with(switch_to_branch, "refs/"))
 547                BUG("Not a fully qualified branch: '%s'", switch_to_branch);
 548
 549        if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0) {
 550                ret = -1;
 551                goto leave_reset_head;
 552        }
 553
 554        if ((!oid || !reset_hard) && get_oid("HEAD", &head_oid)) {
 555                ret = error(_("could not determine HEAD revision"));
 556                goto leave_reset_head;
 557        }
 558
 559        if (!oid)
 560                oid = &head_oid;
 561
 562        memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
 563        setup_unpack_trees_porcelain(&unpack_tree_opts, action);
 564        unpack_tree_opts.head_idx = 1;
 565        unpack_tree_opts.src_index = the_repository->index;
 566        unpack_tree_opts.dst_index = the_repository->index;
 567        unpack_tree_opts.fn = reset_hard ? oneway_merge : twoway_merge;
 568        unpack_tree_opts.update = 1;
 569        unpack_tree_opts.merge = 1;
 570        if (!detach_head)
 571                unpack_tree_opts.reset = 1;
 572
 573        if (read_index_unmerged(the_repository->index) < 0) {
 574                ret = error(_("could not read index"));
 575                goto leave_reset_head;
 576        }
 577
 578        if (!reset_hard && !fill_tree_descriptor(&desc[nr++], &head_oid)) {
 579                ret = error(_("failed to find tree of %s"), oid_to_hex(oid));
 580                goto leave_reset_head;
 581        }
 582
 583        if (!fill_tree_descriptor(&desc[nr++], oid)) {
 584                ret = error(_("failed to find tree of %s"), oid_to_hex(oid));
 585                goto leave_reset_head;
 586        }
 587
 588        if (unpack_trees(nr, desc, &unpack_tree_opts)) {
 589                ret = -1;
 590                goto leave_reset_head;
 591        }
 592
 593        tree = parse_tree_indirect(oid);
 594        prime_cache_tree(the_repository->index, tree);
 595
 596        if (write_locked_index(the_repository->index, &lock, COMMIT_LOCK) < 0) {
 597                ret = error(_("could not write index"));
 598                goto leave_reset_head;
 599        }
 600
 601        reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
 602        strbuf_addf(&msg, "%s: ", reflog_action ? reflog_action : "rebase");
 603        prefix_len = msg.len;
 604
 605        if (!get_oid("ORIG_HEAD", &oid_old_orig))
 606                old_orig = &oid_old_orig;
 607        if (!get_oid("HEAD", &oid_orig)) {
 608                orig = &oid_orig;
 609                if (!reflog_orig_head) {
 610                        strbuf_addstr(&msg, "updating ORIG_HEAD");
 611                        reflog_orig_head = msg.buf;
 612                }
 613                update_ref(reflog_orig_head, "ORIG_HEAD", orig, old_orig, 0,
 614                           UPDATE_REFS_MSG_ON_ERR);
 615        } else if (old_orig)
 616                delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
 617        if (!reflog_head) {
 618                strbuf_setlen(&msg, prefix_len);
 619                strbuf_addstr(&msg, "updating HEAD");
 620                reflog_head = msg.buf;
 621        }
 622        if (!switch_to_branch)
 623                ret = update_ref(reflog_head, "HEAD", oid, orig, REF_NO_DEREF,
 624                                 UPDATE_REFS_MSG_ON_ERR);
 625        else {
 626                ret = create_symref("HEAD", switch_to_branch, msg.buf);
 627                if (!ret)
 628                        ret = update_ref(reflog_head, "HEAD", oid, NULL, 0,
 629                                         UPDATE_REFS_MSG_ON_ERR);
 630        }
 631
 632leave_reset_head:
 633        strbuf_release(&msg);
 634        rollback_lock_file(&lock);
 635        while (nr)
 636                free((void *)desc[--nr].buffer);
 637        return ret;
 638}
 639
 640static int rebase_config(const char *var, const char *value, void *data)
 641{
 642        struct rebase_options *opts = data;
 643
 644        if (!strcmp(var, "rebase.stat")) {
 645                if (git_config_bool(var, value))
 646                        opts->flags |= REBASE_DIFFSTAT;
 647                else
 648                        opts->flags &= !REBASE_DIFFSTAT;
 649                return 0;
 650        }
 651
 652        if (!strcmp(var, "rebase.autosquash")) {
 653                opts->autosquash = git_config_bool(var, value);
 654                return 0;
 655        }
 656
 657        if (!strcmp(var, "commit.gpgsign")) {
 658                free(opts->gpg_sign_opt);
 659                opts->gpg_sign_opt = git_config_bool(var, value) ?
 660                        xstrdup("-S") : NULL;
 661                return 0;
 662        }
 663
 664        if (!strcmp(var, "rebase.autostash")) {
 665                opts->autostash = git_config_bool(var, value);
 666                return 0;
 667        }
 668
 669        return git_default_config(var, value, data);
 670}
 671
 672/*
 673 * Determines whether the commits in from..to are linear, i.e. contain
 674 * no merge commits. This function *expects* `from` to be an ancestor of
 675 * `to`.
 676 */
 677static int is_linear_history(struct commit *from, struct commit *to)
 678{
 679        while (to && to != from) {
 680                parse_commit(to);
 681                if (!to->parents)
 682                        return 1;
 683                if (to->parents->next)
 684                        return 0;
 685                to = to->parents->item;
 686        }
 687        return 1;
 688}
 689
 690static int can_fast_forward(struct commit *onto, struct object_id *head_oid,
 691                            struct object_id *merge_base)
 692{
 693        struct commit *head = lookup_commit(the_repository, head_oid);
 694        struct commit_list *merge_bases;
 695        int res;
 696
 697        if (!head)
 698                return 0;
 699
 700        merge_bases = get_merge_bases(onto, head);
 701        if (merge_bases && !merge_bases->next) {
 702                oidcpy(merge_base, &merge_bases->item->object.oid);
 703                res = oideq(merge_base, &onto->object.oid);
 704        } else {
 705                oidcpy(merge_base, &null_oid);
 706                res = 0;
 707        }
 708        free_commit_list(merge_bases);
 709        return res && is_linear_history(onto, head);
 710}
 711
 712/* -i followed by -m is still -i */
 713static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
 714{
 715        struct rebase_options *opts = opt->value;
 716
 717        if (!is_interactive(opts))
 718                opts->type = REBASE_MERGE;
 719
 720        return 0;
 721}
 722
 723/* -i followed by -p is still explicitly interactive, but -p alone is not */
 724static int parse_opt_interactive(const struct option *opt, const char *arg,
 725                                 int unset)
 726{
 727        struct rebase_options *opts = opt->value;
 728
 729        opts->type = REBASE_INTERACTIVE;
 730        opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
 731
 732        return 0;
 733}
 734
 735static void NORETURN error_on_missing_default_upstream(void)
 736{
 737        struct branch *current_branch = branch_get(NULL);
 738
 739        printf(_("%s\n"
 740                 "Please specify which branch you want to rebase against.\n"
 741                 "See git-rebase(1) for details.\n"
 742                 "\n"
 743                 "    git rebase '<branch>'\n"
 744                 "\n"),
 745                current_branch ? _("There is no tracking information for "
 746                        "the current branch.") :
 747                        _("You are not currently on a branch."));
 748
 749        if (current_branch) {
 750                const char *remote = current_branch->remote_name;
 751
 752                if (!remote)
 753                        remote = _("<remote>");
 754
 755                printf(_("If you wish to set tracking information for this "
 756                         "branch you can do so with:\n"
 757                         "\n"
 758                         "    git branch --set-upstream-to=%s/<branch> %s\n"
 759                         "\n"),
 760                       remote, current_branch->name);
 761        }
 762        exit(1);
 763}
 764
 765int cmd_rebase(int argc, const char **argv, const char *prefix)
 766{
 767        struct rebase_options options = {
 768                .type = REBASE_UNSPECIFIED,
 769                .flags = REBASE_NO_QUIET,
 770                .git_am_opt = STRBUF_INIT,
 771                .allow_rerere_autoupdate  = -1,
 772                .allow_empty_message = 1,
 773                .git_format_patch_opt = STRBUF_INIT,
 774        };
 775        const char *branch_name;
 776        int ret, flags, total_argc, in_progress = 0;
 777        int ok_to_skip_pre_rebase = 0;
 778        struct strbuf msg = STRBUF_INIT;
 779        struct strbuf revisions = STRBUF_INIT;
 780        struct strbuf buf = STRBUF_INIT;
 781        struct object_id merge_base;
 782        enum {
 783                NO_ACTION,
 784                ACTION_CONTINUE,
 785                ACTION_SKIP,
 786                ACTION_ABORT,
 787                ACTION_QUIT,
 788                ACTION_EDIT_TODO,
 789                ACTION_SHOW_CURRENT_PATCH,
 790        } action = NO_ACTION;
 791        int committer_date_is_author_date = 0;
 792        int ignore_date = 0;
 793        int ignore_whitespace = 0;
 794        const char *gpg_sign = NULL;
 795        int opt_c = -1;
 796        struct string_list whitespace = STRING_LIST_INIT_NODUP;
 797        struct string_list exec = STRING_LIST_INIT_NODUP;
 798        const char *rebase_merges = NULL;
 799        int fork_point = -1;
 800        struct string_list strategy_options = STRING_LIST_INIT_NODUP;
 801        struct object_id squash_onto;
 802        char *squash_onto_name = NULL;
 803        struct option builtin_rebase_options[] = {
 804                OPT_STRING(0, "onto", &options.onto_name,
 805                           N_("revision"),
 806                           N_("rebase onto given branch instead of upstream")),
 807                OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
 808                         N_("allow pre-rebase hook to run")),
 809                OPT_NEGBIT('q', "quiet", &options.flags,
 810                           N_("be quiet. implies --no-stat"),
 811                           REBASE_NO_QUIET| REBASE_VERBOSE | REBASE_DIFFSTAT),
 812                OPT_BIT('v', "verbose", &options.flags,
 813                        N_("display a diffstat of what changed upstream"),
 814                        REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
 815                {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
 816                        N_("do not show diffstat of what changed upstream"),
 817                        PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
 818                OPT_BOOL(0, "ignore-whitespace", &ignore_whitespace,
 819                         N_("passed to 'git apply'")),
 820                OPT_BOOL(0, "signoff", &options.signoff,
 821                         N_("add a Signed-off-by: line to each commit")),
 822                OPT_BOOL(0, "committer-date-is-author-date",
 823                         &committer_date_is_author_date,
 824                         N_("passed to 'git am'")),
 825                OPT_BOOL(0, "ignore-date", &ignore_date,
 826                         N_("passed to 'git am'")),
 827                OPT_BIT('f', "force-rebase", &options.flags,
 828                        N_("cherry-pick all commits, even if unchanged"),
 829                        REBASE_FORCE),
 830                OPT_BIT(0, "no-ff", &options.flags,
 831                        N_("cherry-pick all commits, even if unchanged"),
 832                        REBASE_FORCE),
 833                OPT_CMDMODE(0, "continue", &action, N_("continue"),
 834                            ACTION_CONTINUE),
 835                OPT_CMDMODE(0, "skip", &action,
 836                            N_("skip current patch and continue"), ACTION_SKIP),
 837                OPT_CMDMODE(0, "abort", &action,
 838                            N_("abort and check out the original branch"),
 839                            ACTION_ABORT),
 840                OPT_CMDMODE(0, "quit", &action,
 841                            N_("abort but keep HEAD where it is"), ACTION_QUIT),
 842                OPT_CMDMODE(0, "edit-todo", &action, N_("edit the todo list "
 843                            "during an interactive rebase"), ACTION_EDIT_TODO),
 844                OPT_CMDMODE(0, "show-current-patch", &action,
 845                            N_("show the patch file being applied or merged"),
 846                            ACTION_SHOW_CURRENT_PATCH),
 847                { OPTION_CALLBACK, 'm', "merge", &options, NULL,
 848                        N_("use merging strategies to rebase"),
 849                        PARSE_OPT_NOARG | PARSE_OPT_NONEG,
 850                        parse_opt_merge },
 851                { OPTION_CALLBACK, 'i', "interactive", &options, NULL,
 852                        N_("let the user edit the list of commits to rebase"),
 853                        PARSE_OPT_NOARG | PARSE_OPT_NONEG,
 854                        parse_opt_interactive },
 855                OPT_SET_INT('p', "preserve-merges", &options.type,
 856                            N_("try to recreate merges instead of ignoring "
 857                               "them"), REBASE_PRESERVE_MERGES),
 858                OPT_BOOL(0, "rerere-autoupdate",
 859                         &options.allow_rerere_autoupdate,
 860                         N_("allow rerere to update index  with resolved "
 861                            "conflict")),
 862                OPT_BOOL('k', "keep-empty", &options.keep_empty,
 863                         N_("preserve empty commits during rebase")),
 864                OPT_BOOL(0, "autosquash", &options.autosquash,
 865                         N_("move commits that begin with "
 866                            "squash!/fixup! under -i")),
 867                { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
 868                        N_("GPG-sign commits"),
 869                        PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
 870                OPT_STRING_LIST(0, "whitespace", &whitespace,
 871                                N_("whitespace"), N_("passed to 'git apply'")),
 872                OPT_SET_INT('C', NULL, &opt_c, N_("passed to 'git apply'"),
 873                            REBASE_AM),
 874                OPT_BOOL(0, "autostash", &options.autostash,
 875                         N_("automatically stash/stash pop before and after")),
 876                OPT_STRING_LIST('x', "exec", &exec, N_("exec"),
 877                                N_("add exec lines after each commit of the "
 878                                   "editable list")),
 879                OPT_BOOL(0, "allow-empty-message",
 880                         &options.allow_empty_message,
 881                         N_("allow rebasing commits with empty messages")),
 882                {OPTION_STRING, 'r', "rebase-merges", &rebase_merges,
 883                        N_("mode"),
 884                        N_("try to rebase merges instead of skipping them"),
 885                        PARSE_OPT_OPTARG, NULL, (intptr_t)""},
 886                OPT_BOOL(0, "fork-point", &fork_point,
 887                         N_("use 'merge-base --fork-point' to refine upstream")),
 888                OPT_STRING('s', "strategy", &options.strategy,
 889                           N_("strategy"), N_("use the given merge strategy")),
 890                OPT_STRING_LIST('X', "strategy-option", &strategy_options,
 891                                N_("option"),
 892                                N_("pass the argument through to the merge "
 893                                   "strategy")),
 894                OPT_BOOL(0, "root", &options.root,
 895                         N_("rebase all reachable commits up to the root(s)")),
 896                OPT_END(),
 897        };
 898
 899        /*
 900         * NEEDSWORK: Once the builtin rebase has been tested enough
 901         * and git-legacy-rebase.sh is retired to contrib/, this preamble
 902         * can be removed.
 903         */
 904
 905        if (!use_builtin_rebase()) {
 906                const char *path = mkpath("%s/git-legacy-rebase",
 907                                          git_exec_path());
 908
 909                if (sane_execvp(path, (char **)argv) < 0)
 910                        die_errno(_("could not exec %s"), path);
 911                else
 912                        BUG("sane_execvp() returned???");
 913        }
 914
 915        if (argc == 2 && !strcmp(argv[1], "-h"))
 916                usage_with_options(builtin_rebase_usage,
 917                                   builtin_rebase_options);
 918
 919        prefix = setup_git_directory();
 920        trace_repo_setup(prefix);
 921        setup_work_tree();
 922
 923        git_config(rebase_config, &options);
 924
 925        strbuf_reset(&buf);
 926        strbuf_addf(&buf, "%s/applying", apply_dir());
 927        if(file_exists(buf.buf))
 928                die(_("It looks like 'git am' is in progress. Cannot rebase."));
 929
 930        if (is_directory(apply_dir())) {
 931                options.type = REBASE_AM;
 932                options.state_dir = apply_dir();
 933        } else if (is_directory(merge_dir())) {
 934                strbuf_reset(&buf);
 935                strbuf_addf(&buf, "%s/rewritten", merge_dir());
 936                if (is_directory(buf.buf)) {
 937                        options.type = REBASE_PRESERVE_MERGES;
 938                        options.flags |= REBASE_INTERACTIVE_EXPLICIT;
 939                } else {
 940                        strbuf_reset(&buf);
 941                        strbuf_addf(&buf, "%s/interactive", merge_dir());
 942                        if(file_exists(buf.buf)) {
 943                                options.type = REBASE_INTERACTIVE;
 944                                options.flags |= REBASE_INTERACTIVE_EXPLICIT;
 945                        } else
 946                                options.type = REBASE_MERGE;
 947                }
 948                options.state_dir = merge_dir();
 949        }
 950
 951        if (options.type != REBASE_UNSPECIFIED)
 952                in_progress = 1;
 953
 954        total_argc = argc;
 955        argc = parse_options(argc, argv, prefix,
 956                             builtin_rebase_options,
 957                             builtin_rebase_usage, 0);
 958
 959        if (action != NO_ACTION && total_argc != 2) {
 960                usage_with_options(builtin_rebase_usage,
 961                                   builtin_rebase_options);
 962        }
 963
 964        if (argc > 2)
 965                usage_with_options(builtin_rebase_usage,
 966                                   builtin_rebase_options);
 967
 968        if (action != NO_ACTION && !in_progress)
 969                die(_("No rebase in progress?"));
 970
 971        if (action == ACTION_EDIT_TODO && !is_interactive(&options))
 972                die(_("The --edit-todo action can only be used during "
 973                      "interactive rebase."));
 974
 975        switch (action) {
 976        case ACTION_CONTINUE: {
 977                struct object_id head;
 978                struct lock_file lock_file = LOCK_INIT;
 979                int fd;
 980
 981                options.action = "continue";
 982
 983                /* Sanity check */
 984                if (get_oid("HEAD", &head))
 985                        die(_("Cannot read HEAD"));
 986
 987                fd = hold_locked_index(&lock_file, 0);
 988                if (read_index(the_repository->index) < 0)
 989                        die(_("could not read index"));
 990                refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
 991                              NULL);
 992                if (0 <= fd)
 993                        update_index_if_able(the_repository->index,
 994                                             &lock_file);
 995                rollback_lock_file(&lock_file);
 996
 997                if (has_unstaged_changes(1)) {
 998                        puts(_("You must edit all merge conflicts and then\n"
 999                               "mark them as resolved using git add"));
1000                        exit(1);
1001                }
1002                if (read_basic_state(&options))
1003                        exit(1);
1004                goto run_rebase;
1005        }
1006        case ACTION_SKIP: {
1007                struct string_list merge_rr = STRING_LIST_INIT_DUP;
1008
1009                options.action = "skip";
1010
1011                rerere_clear(&merge_rr);
1012                string_list_clear(&merge_rr, 1);
1013
1014                if (reset_head(NULL, "reset", NULL, RESET_HEAD_HARD,
1015                               NULL, NULL) < 0)
1016                        die(_("could not discard worktree changes"));
1017                if (read_basic_state(&options))
1018                        exit(1);
1019                goto run_rebase;
1020        }
1021        case ACTION_ABORT: {
1022                struct string_list merge_rr = STRING_LIST_INIT_DUP;
1023                options.action = "abort";
1024
1025                rerere_clear(&merge_rr);
1026                string_list_clear(&merge_rr, 1);
1027
1028                if (read_basic_state(&options))
1029                        exit(1);
1030                if (reset_head(&options.orig_head, "reset",
1031                               options.head_name, RESET_HEAD_HARD,
1032                               NULL, NULL) < 0)
1033                        die(_("could not move back to %s"),
1034                            oid_to_hex(&options.orig_head));
1035                ret = finish_rebase(&options);
1036                goto cleanup;
1037        }
1038        case ACTION_QUIT: {
1039                strbuf_reset(&buf);
1040                strbuf_addstr(&buf, options.state_dir);
1041                ret = !!remove_dir_recursively(&buf, 0);
1042                if (ret)
1043                        die(_("could not remove '%s'"), options.state_dir);
1044                goto cleanup;
1045        }
1046        case ACTION_EDIT_TODO:
1047                options.action = "edit-todo";
1048                options.dont_finish_rebase = 1;
1049                goto run_rebase;
1050        case ACTION_SHOW_CURRENT_PATCH:
1051                options.action = "show-current-patch";
1052                options.dont_finish_rebase = 1;
1053                goto run_rebase;
1054        case NO_ACTION:
1055                break;
1056        default:
1057                BUG("action: %d", action);
1058        }
1059
1060        /* Make sure no rebase is in progress */
1061        if (in_progress) {
1062                const char *last_slash = strrchr(options.state_dir, '/');
1063                const char *state_dir_base =
1064                        last_slash ? last_slash + 1 : options.state_dir;
1065                const char *cmd_live_rebase =
1066                        "git rebase (--continue | --abort | --skip)";
1067                strbuf_reset(&buf);
1068                strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
1069                die(_("It seems that there is already a %s directory, and\n"
1070                      "I wonder if you are in the middle of another rebase.  "
1071                      "If that is the\n"
1072                      "case, please try\n\t%s\n"
1073                      "If that is not the case, please\n\t%s\n"
1074                      "and run me again.  I am stopping in case you still "
1075                      "have something\n"
1076                      "valuable there.\n"),
1077                    state_dir_base, cmd_live_rebase, buf.buf);
1078        }
1079
1080        if (!(options.flags & REBASE_NO_QUIET))
1081                strbuf_addstr(&options.git_am_opt, " -q");
1082
1083        if (committer_date_is_author_date) {
1084                strbuf_addstr(&options.git_am_opt,
1085                              " --committer-date-is-author-date");
1086                options.flags |= REBASE_FORCE;
1087        }
1088
1089        if (ignore_whitespace)
1090                strbuf_addstr(&options.git_am_opt, " --ignore-whitespace");
1091
1092        if (ignore_date) {
1093                strbuf_addstr(&options.git_am_opt, " --ignore-date");
1094                options.flags |= REBASE_FORCE;
1095        }
1096
1097        if (options.keep_empty)
1098                imply_interactive(&options, "--keep-empty");
1099
1100        if (gpg_sign) {
1101                free(options.gpg_sign_opt);
1102                options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
1103        }
1104
1105        if (opt_c >= 0)
1106                strbuf_addf(&options.git_am_opt, " -C%d", opt_c);
1107
1108        if (whitespace.nr) {
1109                int i;
1110
1111                for (i = 0; i < whitespace.nr; i++) {
1112                        const char *item = whitespace.items[i].string;
1113
1114                        strbuf_addf(&options.git_am_opt, " --whitespace=%s",
1115                                    item);
1116
1117                        if ((!strcmp(item, "fix")) || (!strcmp(item, "strip")))
1118                                options.flags |= REBASE_FORCE;
1119                }
1120        }
1121
1122        if (exec.nr) {
1123                int i;
1124
1125                imply_interactive(&options, "--exec");
1126
1127                strbuf_reset(&buf);
1128                for (i = 0; i < exec.nr; i++)
1129                        strbuf_addf(&buf, "exec %s\n", exec.items[i].string);
1130                options.cmd = xstrdup(buf.buf);
1131        }
1132
1133        if (rebase_merges) {
1134                if (!*rebase_merges)
1135                        ; /* default mode; do nothing */
1136                else if (!strcmp("rebase-cousins", rebase_merges))
1137                        options.rebase_cousins = 1;
1138                else if (strcmp("no-rebase-cousins", rebase_merges))
1139                        die(_("Unknown mode: %s"), rebase_merges);
1140                options.rebase_merges = 1;
1141                imply_interactive(&options, "--rebase-merges");
1142        }
1143
1144        if (strategy_options.nr) {
1145                int i;
1146
1147                if (!options.strategy)
1148                        options.strategy = "recursive";
1149
1150                strbuf_reset(&buf);
1151                for (i = 0; i < strategy_options.nr; i++)
1152                        strbuf_addf(&buf, " --%s",
1153                                    strategy_options.items[i].string);
1154                options.strategy_opts = xstrdup(buf.buf);
1155        }
1156
1157        if (options.strategy) {
1158                options.strategy = xstrdup(options.strategy);
1159                switch (options.type) {
1160                case REBASE_AM:
1161                        die(_("--strategy requires --merge or --interactive"));
1162                case REBASE_MERGE:
1163                case REBASE_INTERACTIVE:
1164                case REBASE_PRESERVE_MERGES:
1165                        /* compatible */
1166                        break;
1167                case REBASE_UNSPECIFIED:
1168                        options.type = REBASE_MERGE;
1169                        break;
1170                default:
1171                        BUG("unhandled rebase type (%d)", options.type);
1172                }
1173        }
1174
1175        if (options.root && !options.onto_name)
1176                imply_interactive(&options, "--root without --onto");
1177
1178        if (isatty(2) && options.flags & REBASE_NO_QUIET)
1179                strbuf_addstr(&options.git_format_patch_opt, " --progress");
1180
1181        switch (options.type) {
1182        case REBASE_MERGE:
1183        case REBASE_INTERACTIVE:
1184        case REBASE_PRESERVE_MERGES:
1185                options.state_dir = merge_dir();
1186                break;
1187        case REBASE_AM:
1188                options.state_dir = apply_dir();
1189                break;
1190        default:
1191                /* the default rebase backend is `--am` */
1192                options.type = REBASE_AM;
1193                options.state_dir = apply_dir();
1194                break;
1195        }
1196
1197        if (options.git_am_opt.len) {
1198                const char *p;
1199
1200                /* all am options except -q are compatible only with --am */
1201                strbuf_reset(&buf);
1202                strbuf_addbuf(&buf, &options.git_am_opt);
1203                strbuf_addch(&buf, ' ');
1204                while ((p = strstr(buf.buf, " -q ")))
1205                        strbuf_splice(&buf, p - buf.buf, 4, " ", 1);
1206                strbuf_trim(&buf);
1207
1208                if (is_interactive(&options) && buf.len)
1209                        die(_("error: cannot combine interactive options "
1210                              "(--interactive, --exec, --rebase-merges, "
1211                              "--preserve-merges, --keep-empty, --root + "
1212                              "--onto) with am options (%s)"), buf.buf);
1213                if (options.type == REBASE_MERGE && buf.len)
1214                        die(_("error: cannot combine merge options (--merge, "
1215                              "--strategy, --strategy-option) with am options "
1216                              "(%s)"), buf.buf);
1217        }
1218
1219        if (options.signoff) {
1220                if (options.type == REBASE_PRESERVE_MERGES)
1221                        die("cannot combine '--signoff' with "
1222                            "'--preserve-merges'");
1223                strbuf_addstr(&options.git_am_opt, " --signoff");
1224                options.flags |= REBASE_FORCE;
1225        }
1226
1227        if (options.type == REBASE_PRESERVE_MERGES)
1228                /*
1229                 * Note: incompatibility with --signoff handled in signoff block above
1230                 * Note: incompatibility with --interactive is just a strong warning;
1231                 *       git-rebase.txt caveats with "unless you know what you are doing"
1232                 */
1233                if (options.rebase_merges)
1234                        die(_("error: cannot combine '--preserve-merges' with "
1235                              "'--rebase-merges'"));
1236
1237        if (options.rebase_merges) {
1238                if (strategy_options.nr)
1239                        die(_("error: cannot combine '--rebase-merges' with "
1240                              "'--strategy-option'"));
1241                if (options.strategy)
1242                        die(_("error: cannot combine '--rebase-merges' with "
1243                              "'--strategy'"));
1244        }
1245
1246        if (!options.root) {
1247                if (argc < 1) {
1248                        struct branch *branch;
1249
1250                        branch = branch_get(NULL);
1251                        options.upstream_name = branch_get_upstream(branch,
1252                                                                    NULL);
1253                        if (!options.upstream_name)
1254                                error_on_missing_default_upstream();
1255                        if (fork_point < 0)
1256                                fork_point = 1;
1257                } else {
1258                        options.upstream_name = argv[0];
1259                        argc--;
1260                        argv++;
1261                        if (!strcmp(options.upstream_name, "-"))
1262                                options.upstream_name = "@{-1}";
1263                }
1264                options.upstream = peel_committish(options.upstream_name);
1265                if (!options.upstream)
1266                        die(_("invalid upstream '%s'"), options.upstream_name);
1267                options.upstream_arg = options.upstream_name;
1268        } else {
1269                if (!options.onto_name) {
1270                        if (commit_tree("", 0, the_hash_algo->empty_tree, NULL,
1271                                        &squash_onto, NULL, NULL) < 0)
1272                                die(_("Could not create new root commit"));
1273                        options.squash_onto = &squash_onto;
1274                        options.onto_name = squash_onto_name =
1275                                xstrdup(oid_to_hex(&squash_onto));
1276                }
1277                options.upstream_name = NULL;
1278                options.upstream = NULL;
1279                if (argc > 1)
1280                        usage_with_options(builtin_rebase_usage,
1281                                           builtin_rebase_options);
1282                options.upstream_arg = "--root";
1283        }
1284
1285        /* Make sure the branch to rebase onto is valid. */
1286        if (!options.onto_name)
1287                options.onto_name = options.upstream_name;
1288        if (strstr(options.onto_name, "...")) {
1289                if (get_oid_mb(options.onto_name, &merge_base) < 0)
1290                        die(_("'%s': need exactly one merge base"),
1291                            options.onto_name);
1292                options.onto = lookup_commit_or_die(&merge_base,
1293                                                    options.onto_name);
1294        } else {
1295                options.onto = peel_committish(options.onto_name);
1296                if (!options.onto)
1297                        die(_("Does not point to a valid commit '%s'"),
1298                                options.onto_name);
1299        }
1300
1301        /*
1302         * If the branch to rebase is given, that is the branch we will rebase
1303         * branch_name -- branch/commit being rebased, or
1304         *                HEAD (already detached)
1305         * orig_head -- commit object name of tip of the branch before rebasing
1306         * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
1307         */
1308        if (argc == 1) {
1309                /* Is it "rebase other branchname" or "rebase other commit"? */
1310                branch_name = argv[0];
1311                options.switch_to = argv[0];
1312
1313                /* Is it a local branch? */
1314                strbuf_reset(&buf);
1315                strbuf_addf(&buf, "refs/heads/%s", branch_name);
1316                if (!read_ref(buf.buf, &options.orig_head))
1317                        options.head_name = xstrdup(buf.buf);
1318                /* If not is it a valid ref (branch or commit)? */
1319                else if (!get_oid(branch_name, &options.orig_head))
1320                        options.head_name = NULL;
1321                else
1322                        die(_("fatal: no such branch/commit '%s'"),
1323                            branch_name);
1324        } else if (argc == 0) {
1325                /* Do not need to switch branches, we are already on it. */
1326                options.head_name =
1327                        xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
1328                                         &flags));
1329                if (!options.head_name)
1330                        die(_("No such ref: %s"), "HEAD");
1331                if (flags & REF_ISSYMREF) {
1332                        if (!skip_prefix(options.head_name,
1333                                         "refs/heads/", &branch_name))
1334                                branch_name = options.head_name;
1335
1336                } else {
1337                        free(options.head_name);
1338                        options.head_name = NULL;
1339                        branch_name = "HEAD";
1340                }
1341                if (get_oid("HEAD", &options.orig_head))
1342                        die(_("Could not resolve HEAD to a revision"));
1343        } else
1344                BUG("unexpected number of arguments left to parse");
1345
1346        if (fork_point > 0) {
1347                struct commit *head =
1348                        lookup_commit_reference(the_repository,
1349                                                &options.orig_head);
1350                options.restrict_revision =
1351                        get_fork_point(options.upstream_name, head);
1352        }
1353
1354        if (read_index(the_repository->index) < 0)
1355                die(_("could not read index"));
1356
1357        if (options.autostash) {
1358                struct lock_file lock_file = LOCK_INIT;
1359                int fd;
1360
1361                fd = hold_locked_index(&lock_file, 0);
1362                refresh_cache(REFRESH_QUIET);
1363                if (0 <= fd)
1364                        update_index_if_able(&the_index, &lock_file);
1365                rollback_lock_file(&lock_file);
1366
1367                if (has_unstaged_changes(1) || has_uncommitted_changes(1)) {
1368                        const char *autostash =
1369                                state_dir_path("autostash", &options);
1370                        struct child_process stash = CHILD_PROCESS_INIT;
1371                        struct object_id oid;
1372                        struct commit *head =
1373                                lookup_commit_reference(the_repository,
1374                                                        &options.orig_head);
1375
1376                        argv_array_pushl(&stash.args,
1377                                         "stash", "create", "autostash", NULL);
1378                        stash.git_cmd = 1;
1379                        stash.no_stdin = 1;
1380                        strbuf_reset(&buf);
1381                        if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
1382                                die(_("Cannot autostash"));
1383                        strbuf_trim_trailing_newline(&buf);
1384                        if (get_oid(buf.buf, &oid))
1385                                die(_("Unexpected stash response: '%s'"),
1386                                    buf.buf);
1387                        strbuf_reset(&buf);
1388                        strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
1389
1390                        if (safe_create_leading_directories_const(autostash))
1391                                die(_("Could not create directory for '%s'"),
1392                                    options.state_dir);
1393                        write_file(autostash, "%s", oid_to_hex(&oid));
1394                        printf(_("Created autostash: %s\n"), buf.buf);
1395                        if (reset_head(&head->object.oid, "reset --hard",
1396                                       NULL, RESET_HEAD_HARD, NULL, NULL) < 0)
1397                                die(_("could not reset --hard"));
1398                        printf(_("HEAD is now at %s"),
1399                               find_unique_abbrev(&head->object.oid,
1400                                                  DEFAULT_ABBREV));
1401                        strbuf_reset(&buf);
1402                        pp_commit_easy(CMIT_FMT_ONELINE, head, &buf);
1403                        if (buf.len > 0)
1404                                printf(" %s", buf.buf);
1405                        putchar('\n');
1406
1407                        if (discard_index(the_repository->index) < 0 ||
1408                                read_index(the_repository->index) < 0)
1409                                die(_("could not read index"));
1410                }
1411        }
1412
1413        if (require_clean_work_tree("rebase",
1414                                    _("Please commit or stash them."), 1, 1)) {
1415                ret = 1;
1416                goto cleanup;
1417        }
1418
1419        /*
1420         * Now we are rebasing commits upstream..orig_head (or with --root,
1421         * everything leading up to orig_head) on top of onto.
1422         */
1423
1424        /*
1425         * Check if we are already based on onto with linear history,
1426         * but this should be done only when upstream and onto are the same
1427         * and if this is not an interactive rebase.
1428         */
1429        if (can_fast_forward(options.onto, &options.orig_head, &merge_base) &&
1430            !is_interactive(&options) && !options.restrict_revision &&
1431            options.upstream &&
1432            !oidcmp(&options.upstream->object.oid, &options.onto->object.oid)) {
1433                int flag;
1434
1435                if (!(options.flags & REBASE_FORCE)) {
1436                        /* Lazily switch to the target branch if needed... */
1437                        if (options.switch_to) {
1438                                struct object_id oid;
1439
1440                                if (get_oid(options.switch_to, &oid) < 0) {
1441                                        ret = !!error(_("could not parse '%s'"),
1442                                                      options.switch_to);
1443                                        goto cleanup;
1444                                }
1445
1446                                strbuf_reset(&buf);
1447                                strbuf_addf(&buf, "rebase: checkout %s",
1448                                            options.switch_to);
1449                                if (reset_head(&oid, "checkout",
1450                                               options.head_name, 0,
1451                                               NULL, NULL) < 0) {
1452                                        ret = !!error(_("could not switch to "
1453                                                        "%s"),
1454                                                      options.switch_to);
1455                                        goto cleanup;
1456                                }
1457                        }
1458
1459                        if (!(options.flags & REBASE_NO_QUIET))
1460                                ; /* be quiet */
1461                        else if (!strcmp(branch_name, "HEAD") &&
1462                                 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1463                                puts(_("HEAD is up to date."));
1464                        else
1465                                printf(_("Current branch %s is up to date.\n"),
1466                                       branch_name);
1467                        ret = !!finish_rebase(&options);
1468                        goto cleanup;
1469                } else if (!(options.flags & REBASE_NO_QUIET))
1470                        ; /* be quiet */
1471                else if (!strcmp(branch_name, "HEAD") &&
1472                         resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1473                        puts(_("HEAD is up to date, rebase forced."));
1474                else
1475                        printf(_("Current branch %s is up to date, rebase "
1476                                 "forced.\n"), branch_name);
1477        }
1478
1479        /* If a hook exists, give it a chance to interrupt*/
1480        if (!ok_to_skip_pre_rebase &&
1481            run_hook_le(NULL, "pre-rebase", options.upstream_arg,
1482                        argc ? argv[0] : NULL, NULL))
1483                die(_("The pre-rebase hook refused to rebase."));
1484
1485        if (options.flags & REBASE_DIFFSTAT) {
1486                struct diff_options opts;
1487
1488                if (options.flags & REBASE_VERBOSE)
1489                        printf(_("Changes from %s to %s:\n"),
1490                                oid_to_hex(&merge_base),
1491                                oid_to_hex(&options.onto->object.oid));
1492
1493                /* We want color (if set), but no pager */
1494                diff_setup(&opts);
1495                opts.stat_width = -1; /* use full terminal width */
1496                opts.stat_graph_width = -1; /* respect statGraphWidth config */
1497                opts.output_format |=
1498                        DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1499                opts.detect_rename = DIFF_DETECT_RENAME;
1500                diff_setup_done(&opts);
1501                diff_tree_oid(&merge_base, &options.onto->object.oid,
1502                              "", &opts);
1503                diffcore_std(&opts);
1504                diff_flush(&opts);
1505        }
1506
1507        if (is_interactive(&options))
1508                goto run_rebase;
1509
1510        /* Detach HEAD and reset the tree */
1511        if (options.flags & REBASE_NO_QUIET)
1512                printf(_("First, rewinding head to replay your work on top of "
1513                         "it...\n"));
1514
1515        strbuf_addf(&msg, "rebase: checkout %s", options.onto_name);
1516        if (reset_head(&options.onto->object.oid, "checkout", NULL,
1517                       RESET_HEAD_DETACH, NULL, msg.buf))
1518                die(_("Could not detach HEAD"));
1519        strbuf_release(&msg);
1520
1521        /*
1522         * If the onto is a proper descendant of the tip of the branch, then
1523         * we just fast-forwarded.
1524         */
1525        strbuf_reset(&msg);
1526        if (!oidcmp(&merge_base, &options.orig_head)) {
1527                printf(_("Fast-forwarded %s to %s. \n"),
1528                        branch_name, options.onto_name);
1529                strbuf_addf(&msg, "rebase finished: %s onto %s",
1530                        options.head_name ? options.head_name : "detached HEAD",
1531                        oid_to_hex(&options.onto->object.oid));
1532                reset_head(NULL, "Fast-forwarded", options.head_name, 0,
1533                           "HEAD", msg.buf);
1534                strbuf_release(&msg);
1535                ret = !!finish_rebase(&options);
1536                goto cleanup;
1537        }
1538
1539        strbuf_addf(&revisions, "%s..%s",
1540                    options.root ? oid_to_hex(&options.onto->object.oid) :
1541                    (options.restrict_revision ?
1542                     oid_to_hex(&options.restrict_revision->object.oid) :
1543                     oid_to_hex(&options.upstream->object.oid)),
1544                    oid_to_hex(&options.orig_head));
1545
1546        options.revisions = revisions.buf;
1547
1548run_rebase:
1549        ret = !!run_specific_rebase(&options);
1550
1551cleanup:
1552        strbuf_release(&revisions);
1553        free(options.head_name);
1554        free(options.gpg_sign_opt);
1555        free(options.cmd);
1556        free(squash_onto_name);
1557        return ret;
1558}