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