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