builtin / rebase.con commit rebase -i: remove duplication (c44c246)
   1/*
   2 * "git rebase" builtin command
   3 *
   4 * Copyright (c) 2018 Pratik Karki
   5 */
   6
   7#define USE_THE_INDEX_COMPATIBILITY_MACROS
   8#include "builtin.h"
   9#include "run-command.h"
  10#include "exec-cmd.h"
  11#include "argv-array.h"
  12#include "dir.h"
  13#include "packfile.h"
  14#include "refs.h"
  15#include "quote.h"
  16#include "config.h"
  17#include "cache-tree.h"
  18#include "unpack-trees.h"
  19#include "lockfile.h"
  20#include "parse-options.h"
  21#include "commit.h"
  22#include "diff.h"
  23#include "wt-status.h"
  24#include "revision.h"
  25#include "commit-reach.h"
  26#include "rerere.h"
  27#include "branch.h"
  28#include "sequencer.h"
  29#include "rebase-interactive.h"
  30
  31static char const * const builtin_rebase_usage[] = {
  32        N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
  33                "[<upstream>] [<branch>]"),
  34        N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
  35                "--root [<branch>]"),
  36        N_("git rebase --continue | --abort | --skip | --edit-todo"),
  37        NULL
  38};
  39
  40static GIT_PATH_FUNC(path_squash_onto, "rebase-merge/squash-onto")
  41static GIT_PATH_FUNC(path_interactive, "rebase-merge/interactive")
  42static GIT_PATH_FUNC(apply_dir, "rebase-apply")
  43static GIT_PATH_FUNC(merge_dir, "rebase-merge")
  44
  45enum rebase_type {
  46        REBASE_UNSPECIFIED = -1,
  47        REBASE_AM,
  48        REBASE_MERGE,
  49        REBASE_INTERACTIVE,
  50        REBASE_PRESERVE_MERGES
  51};
  52
  53static int add_exec_commands(struct string_list *commands)
  54{
  55        const char *todo_file = rebase_path_todo();
  56        struct todo_list todo_list = TODO_LIST_INIT;
  57        int res;
  58
  59        if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
  60                return error_errno(_("could not read '%s'."), todo_file);
  61
  62        if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
  63                                        &todo_list)) {
  64                todo_list_release(&todo_list);
  65                return error(_("unusable todo list: '%s'"), todo_file);
  66        }
  67
  68        todo_list_add_exec_commands(&todo_list, commands);
  69        res = todo_list_write_to_file(the_repository, &todo_list,
  70                                      todo_file, NULL, NULL, -1, 0);
  71        todo_list_release(&todo_list);
  72
  73        if (res)
  74                return error_errno(_("could not write '%s'."), todo_file);
  75        return 0;
  76}
  77
  78static int rearrange_squash_in_todo_file(void)
  79{
  80        const char *todo_file = rebase_path_todo();
  81        struct todo_list todo_list = TODO_LIST_INIT;
  82        int res = 0;
  83
  84        if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
  85                return error_errno(_("could not read '%s'."), todo_file);
  86        if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
  87                                        &todo_list)) {
  88                todo_list_release(&todo_list);
  89                return error(_("unusable todo list: '%s'"), todo_file);
  90        }
  91
  92        res = todo_list_rearrange_squash(&todo_list);
  93        if (!res)
  94                res = todo_list_write_to_file(the_repository, &todo_list,
  95                                              todo_file, NULL, NULL, -1, 0);
  96
  97        todo_list_release(&todo_list);
  98
  99        if (res)
 100                return error_errno(_("could not write '%s'."), todo_file);
 101        return 0;
 102}
 103
 104static int transform_todo_file(unsigned flags)
 105{
 106        const char *todo_file = rebase_path_todo();
 107        struct todo_list todo_list = TODO_LIST_INIT;
 108        int res;
 109
 110        if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
 111                return error_errno(_("could not read '%s'."), todo_file);
 112
 113        if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
 114                                        &todo_list)) {
 115                todo_list_release(&todo_list);
 116                return error(_("unusable todo list: '%s'"), todo_file);
 117        }
 118
 119        res = todo_list_write_to_file(the_repository, &todo_list, todo_file,
 120                                      NULL, NULL, -1, flags);
 121        todo_list_release(&todo_list);
 122
 123        if (res)
 124                return error_errno(_("could not write '%s'."), todo_file);
 125        return 0;
 126}
 127
 128static int edit_todo_file(unsigned flags)
 129{
 130        const char *todo_file = rebase_path_todo();
 131        struct todo_list todo_list = TODO_LIST_INIT,
 132                new_todo = TODO_LIST_INIT;
 133        int res = 0;
 134
 135        if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
 136                return error_errno(_("could not read '%s'."), todo_file);
 137
 138        strbuf_stripspace(&todo_list.buf, 1);
 139        res = edit_todo_list(the_repository, &todo_list, &new_todo, NULL, NULL, flags);
 140        if (!res && todo_list_write_to_file(the_repository, &new_todo, todo_file,
 141                                            NULL, NULL, -1, flags & ~(TODO_LIST_SHORTEN_IDS)))
 142                res = error_errno(_("could not write '%s'"), todo_file);
 143
 144        todo_list_release(&todo_list);
 145        todo_list_release(&new_todo);
 146
 147        return res;
 148}
 149
 150static int get_revision_ranges(const char *upstream, const char *onto,
 151                               const char **head_hash,
 152                               char **revisions, char **shortrevisions)
 153{
 154        const char *base_rev = upstream ? upstream : onto, *shorthead;
 155        struct object_id orig_head;
 156
 157        if (get_oid("HEAD", &orig_head))
 158                return error(_("no HEAD?"));
 159
 160        *head_hash = find_unique_abbrev(&orig_head, GIT_MAX_HEXSZ);
 161        *revisions = xstrfmt("%s...%s", base_rev, *head_hash);
 162
 163        shorthead = find_unique_abbrev(&orig_head, DEFAULT_ABBREV);
 164
 165        if (upstream) {
 166                const char *shortrev;
 167                struct object_id rev_oid;
 168
 169                get_oid(base_rev, &rev_oid);
 170                shortrev = find_unique_abbrev(&rev_oid, DEFAULT_ABBREV);
 171
 172                *shortrevisions = xstrfmt("%s..%s", shortrev, shorthead);
 173        } else
 174                *shortrevisions = xstrdup(shorthead);
 175
 176        return 0;
 177}
 178
 179static int init_basic_state(struct replay_opts *opts, const char *head_name,
 180                            const char *onto, const char *orig_head)
 181{
 182        FILE *interactive;
 183
 184        if (!is_directory(merge_dir()) && mkdir_in_gitdir(merge_dir()))
 185                return error_errno(_("could not create temporary %s"), merge_dir());
 186
 187        delete_reflog("REBASE_HEAD");
 188
 189        interactive = fopen(path_interactive(), "w");
 190        if (!interactive)
 191                return error_errno(_("could not mark as interactive"));
 192        fclose(interactive);
 193
 194        return write_basic_state(opts, head_name, onto, orig_head);
 195}
 196
 197static int do_interactive_rebase(struct replay_opts *opts, unsigned flags,
 198                                 const char *switch_to, const char *upstream,
 199                                 const char *onto, const char *onto_name,
 200                                 const char *squash_onto, const char *head_name,
 201                                 const char *restrict_revision, char *raw_strategies,
 202                                 struct string_list *commands, unsigned autosquash)
 203{
 204        int ret;
 205        const char *head_hash = NULL;
 206        char *revisions = NULL, *shortrevisions = NULL;
 207        struct argv_array make_script_args = ARGV_ARRAY_INIT;
 208        struct todo_list todo_list = TODO_LIST_INIT;
 209
 210        if (prepare_branch_to_be_rebased(the_repository, opts, switch_to))
 211                return -1;
 212
 213        if (get_revision_ranges(upstream, onto, &head_hash,
 214                                &revisions, &shortrevisions))
 215                return -1;
 216
 217        if (raw_strategies)
 218                parse_strategy_opts(opts, raw_strategies);
 219
 220        if (init_basic_state(opts, head_name, onto, head_hash)) {
 221                free(revisions);
 222                free(shortrevisions);
 223
 224                return -1;
 225        }
 226
 227        if (!upstream && squash_onto)
 228                write_file(path_squash_onto(), "%s\n", squash_onto);
 229
 230        argv_array_pushl(&make_script_args, "", revisions, NULL);
 231        if (restrict_revision)
 232                argv_array_push(&make_script_args, restrict_revision);
 233
 234        ret = sequencer_make_script(the_repository, &todo_list.buf,
 235                                    make_script_args.argc, make_script_args.argv,
 236                                    flags);
 237
 238        if (ret)
 239                error(_("could not generate todo list"));
 240        else {
 241                discard_cache();
 242                if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
 243                                                &todo_list))
 244                        BUG("unusable todo list");
 245
 246                ret = complete_action(the_repository, opts, flags, shortrevisions, onto_name,
 247                                      onto, head_hash, commands, autosquash, &todo_list);
 248        }
 249
 250        free(revisions);
 251        free(shortrevisions);
 252        todo_list_release(&todo_list);
 253        argv_array_clear(&make_script_args);
 254
 255        return ret;
 256}
 257
 258static const char * const builtin_rebase_interactive_usage[] = {
 259        N_("git rebase--interactive [<options>]"),
 260        NULL
 261};
 262
 263int cmd_rebase__interactive(int argc, const char **argv, const char *prefix)
 264{
 265        struct replay_opts opts = REPLAY_OPTS_INIT;
 266        unsigned flags = 0, keep_empty = 0, rebase_merges = 0, autosquash = 0;
 267        int abbreviate_commands = 0, rebase_cousins = -1, ret = 0;
 268        const char *onto = NULL, *onto_name = NULL, *restrict_revision = NULL,
 269                *squash_onto = NULL, *upstream = NULL, *head_name = NULL,
 270                *switch_to = NULL, *cmd = NULL;
 271        struct string_list commands = STRING_LIST_INIT_DUP;
 272        char *raw_strategies = NULL;
 273        enum {
 274                NONE = 0, CONTINUE, SKIP, EDIT_TODO, SHOW_CURRENT_PATCH,
 275                SHORTEN_OIDS, EXPAND_OIDS, CHECK_TODO_LIST, REARRANGE_SQUASH, ADD_EXEC
 276        } command = 0;
 277        struct option options[] = {
 278                OPT_BOOL(0, "ff", &opts.allow_ff, N_("allow fast-forward")),
 279                OPT_BOOL(0, "keep-empty", &keep_empty, N_("keep empty commits")),
 280                OPT_BOOL(0, "allow-empty-message", &opts.allow_empty_message,
 281                         N_("allow commits with empty messages")),
 282                OPT_BOOL(0, "rebase-merges", &rebase_merges, N_("rebase merge commits")),
 283                OPT_BOOL(0, "rebase-cousins", &rebase_cousins,
 284                         N_("keep original branch points of cousins")),
 285                OPT_BOOL(0, "autosquash", &autosquash,
 286                         N_("move commits that begin with squash!/fixup!")),
 287                OPT_BOOL(0, "signoff", &opts.signoff, N_("sign commits")),
 288                OPT__VERBOSE(&opts.verbose, N_("be verbose")),
 289                OPT_CMDMODE(0, "continue", &command, N_("continue rebase"),
 290                            CONTINUE),
 291                OPT_CMDMODE(0, "skip", &command, N_("skip commit"), SKIP),
 292                OPT_CMDMODE(0, "edit-todo", &command, N_("edit the todo list"),
 293                            EDIT_TODO),
 294                OPT_CMDMODE(0, "show-current-patch", &command, N_("show the current patch"),
 295                            SHOW_CURRENT_PATCH),
 296                OPT_CMDMODE(0, "shorten-ids", &command,
 297                        N_("shorten commit ids in the todo list"), SHORTEN_OIDS),
 298                OPT_CMDMODE(0, "expand-ids", &command,
 299                        N_("expand commit ids in the todo list"), EXPAND_OIDS),
 300                OPT_CMDMODE(0, "check-todo-list", &command,
 301                        N_("check the todo list"), CHECK_TODO_LIST),
 302                OPT_CMDMODE(0, "rearrange-squash", &command,
 303                        N_("rearrange fixup/squash lines"), REARRANGE_SQUASH),
 304                OPT_CMDMODE(0, "add-exec-commands", &command,
 305                        N_("insert exec commands in todo list"), ADD_EXEC),
 306                OPT_STRING(0, "onto", &onto, N_("onto"), N_("onto")),
 307                OPT_STRING(0, "restrict-revision", &restrict_revision,
 308                           N_("restrict-revision"), N_("restrict revision")),
 309                OPT_STRING(0, "squash-onto", &squash_onto, N_("squash-onto"),
 310                           N_("squash onto")),
 311                OPT_STRING(0, "upstream", &upstream, N_("upstream"),
 312                           N_("the upstream commit")),
 313                OPT_STRING(0, "head-name", &head_name, N_("head-name"), N_("head name")),
 314                { OPTION_STRING, 'S', "gpg-sign", &opts.gpg_sign, N_("key-id"),
 315                        N_("GPG-sign commits"),
 316                        PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
 317                OPT_STRING(0, "strategy", &opts.strategy, N_("strategy"),
 318                           N_("rebase strategy")),
 319                OPT_STRING(0, "strategy-opts", &raw_strategies, N_("strategy-opts"),
 320                           N_("strategy options")),
 321                OPT_STRING(0, "switch-to", &switch_to, N_("switch-to"),
 322                           N_("the branch or commit to checkout")),
 323                OPT_STRING(0, "onto-name", &onto_name, N_("onto-name"), N_("onto name")),
 324                OPT_STRING(0, "cmd", &cmd, N_("cmd"), N_("the command to run")),
 325                OPT_RERERE_AUTOUPDATE(&opts.allow_rerere_auto),
 326                OPT_BOOL(0, "reschedule-failed-exec", &opts.reschedule_failed_exec,
 327                         N_("automatically re-schedule any `exec` that fails")),
 328                OPT_END()
 329        };
 330
 331        sequencer_init_config(&opts);
 332        git_config_get_bool("rebase.abbreviatecommands", &abbreviate_commands);
 333
 334        opts.action = REPLAY_INTERACTIVE_REBASE;
 335        opts.allow_ff = 1;
 336        opts.allow_empty = 1;
 337
 338        if (argc == 1)
 339                usage_with_options(builtin_rebase_interactive_usage, options);
 340
 341        argc = parse_options(argc, argv, NULL, options,
 342                        builtin_rebase_interactive_usage, PARSE_OPT_KEEP_ARGV0);
 343
 344        opts.gpg_sign = xstrdup_or_null(opts.gpg_sign);
 345
 346        flags |= keep_empty ? TODO_LIST_KEEP_EMPTY : 0;
 347        flags |= abbreviate_commands ? TODO_LIST_ABBREVIATE_CMDS : 0;
 348        flags |= rebase_merges ? TODO_LIST_REBASE_MERGES : 0;
 349        flags |= rebase_cousins > 0 ? TODO_LIST_REBASE_COUSINS : 0;
 350        flags |= command == SHORTEN_OIDS ? TODO_LIST_SHORTEN_IDS : 0;
 351
 352        if (rebase_cousins >= 0 && !rebase_merges)
 353                warning(_("--[no-]rebase-cousins has no effect without "
 354                          "--rebase-merges"));
 355
 356        if (cmd && *cmd) {
 357                string_list_split(&commands, cmd, '\n', -1);
 358
 359                /* rebase.c adds a new line to cmd after every command,
 360                 * so here the last command is always empty */
 361                string_list_remove_empty_items(&commands, 0);
 362        }
 363
 364        switch (command) {
 365        case NONE:
 366                if (!onto && !upstream)
 367                        die(_("a base commit must be provided with --upstream or --onto"));
 368
 369                ret = do_interactive_rebase(&opts, flags, switch_to, upstream, onto,
 370                                            onto_name, squash_onto, head_name, restrict_revision,
 371                                            raw_strategies, &commands, autosquash);
 372                break;
 373        case SKIP: {
 374                struct string_list merge_rr = STRING_LIST_INIT_DUP;
 375
 376                rerere_clear(the_repository, &merge_rr);
 377                /* fallthrough */
 378        case CONTINUE:
 379                ret = sequencer_continue(the_repository, &opts);
 380                break;
 381        }
 382        case EDIT_TODO:
 383                ret = edit_todo_file(flags);
 384                break;
 385        case SHOW_CURRENT_PATCH: {
 386                struct child_process cmd = CHILD_PROCESS_INIT;
 387
 388                cmd.git_cmd = 1;
 389                argv_array_pushl(&cmd.args, "show", "REBASE_HEAD", "--", NULL);
 390                ret = run_command(&cmd);
 391
 392                break;
 393        }
 394        case SHORTEN_OIDS:
 395        case EXPAND_OIDS:
 396                ret = transform_todo_file(flags);
 397                break;
 398        case CHECK_TODO_LIST:
 399                ret = check_todo_list_from_file(the_repository);
 400                break;
 401        case REARRANGE_SQUASH:
 402                ret = rearrange_squash_in_todo_file();
 403                break;
 404        case ADD_EXEC:
 405                ret = add_exec_commands(&commands);
 406                break;
 407        default:
 408                BUG("invalid command '%d'", command);
 409        }
 410
 411        string_list_clear(&commands, 0);
 412        return !!ret;
 413}
 414
 415static int use_builtin_rebase(void)
 416{
 417        struct child_process cp = CHILD_PROCESS_INIT;
 418        struct strbuf out = STRBUF_INIT;
 419        int ret, env = git_env_bool("GIT_TEST_REBASE_USE_BUILTIN", -1);
 420
 421        if (env != -1)
 422                return env;
 423
 424        argv_array_pushl(&cp.args,
 425                         "config", "--bool", "rebase.usebuiltin", NULL);
 426        cp.git_cmd = 1;
 427        if (capture_command(&cp, &out, 6)) {
 428                strbuf_release(&out);
 429                return 1;
 430        }
 431
 432        strbuf_trim(&out);
 433        ret = !strcmp("true", out.buf);
 434        strbuf_release(&out);
 435        return ret;
 436}
 437
 438struct rebase_options {
 439        enum rebase_type type;
 440        const char *state_dir;
 441        struct commit *upstream;
 442        const char *upstream_name;
 443        const char *upstream_arg;
 444        char *head_name;
 445        struct object_id orig_head;
 446        struct commit *onto;
 447        const char *onto_name;
 448        const char *revisions;
 449        const char *switch_to;
 450        int root;
 451        struct object_id *squash_onto;
 452        struct commit *restrict_revision;
 453        int dont_finish_rebase;
 454        enum {
 455                REBASE_NO_QUIET = 1<<0,
 456                REBASE_VERBOSE = 1<<1,
 457                REBASE_DIFFSTAT = 1<<2,
 458                REBASE_FORCE = 1<<3,
 459                REBASE_INTERACTIVE_EXPLICIT = 1<<4,
 460        } flags;
 461        struct argv_array git_am_opts;
 462        const char *action;
 463        int signoff;
 464        int allow_rerere_autoupdate;
 465        int keep_empty;
 466        int autosquash;
 467        char *gpg_sign_opt;
 468        int autostash;
 469        char *cmd;
 470        int allow_empty_message;
 471        int rebase_merges, rebase_cousins;
 472        char *strategy, *strategy_opts;
 473        struct strbuf git_format_patch_opt;
 474        int reschedule_failed_exec;
 475};
 476
 477static int is_interactive(struct rebase_options *opts)
 478{
 479        return opts->type == REBASE_INTERACTIVE ||
 480                opts->type == REBASE_PRESERVE_MERGES;
 481}
 482
 483static void imply_interactive(struct rebase_options *opts, const char *option)
 484{
 485        switch (opts->type) {
 486        case REBASE_AM:
 487                die(_("%s requires an interactive rebase"), option);
 488                break;
 489        case REBASE_INTERACTIVE:
 490        case REBASE_PRESERVE_MERGES:
 491                break;
 492        case REBASE_MERGE:
 493                /* we now implement --merge via --interactive */
 494        default:
 495                opts->type = REBASE_INTERACTIVE; /* implied */
 496                break;
 497        }
 498}
 499
 500/* Returns the filename prefixed by the state_dir */
 501static const char *state_dir_path(const char *filename, struct rebase_options *opts)
 502{
 503        static struct strbuf path = STRBUF_INIT;
 504        static size_t prefix_len;
 505
 506        if (!prefix_len) {
 507                strbuf_addf(&path, "%s/", opts->state_dir);
 508                prefix_len = path.len;
 509        }
 510
 511        strbuf_setlen(&path, prefix_len);
 512        strbuf_addstr(&path, filename);
 513        return path.buf;
 514}
 515
 516/* Read one file, then strip line endings */
 517static int read_one(const char *path, struct strbuf *buf)
 518{
 519        if (strbuf_read_file(buf, path, 0) < 0)
 520                return error_errno(_("could not read '%s'"), path);
 521        strbuf_trim_trailing_newline(buf);
 522        return 0;
 523}
 524
 525/* Initialize the rebase options from the state directory. */
 526static int read_basic_state(struct rebase_options *opts)
 527{
 528        struct strbuf head_name = STRBUF_INIT;
 529        struct strbuf buf = STRBUF_INIT;
 530        struct object_id oid;
 531
 532        if (read_one(state_dir_path("head-name", opts), &head_name) ||
 533            read_one(state_dir_path("onto", opts), &buf))
 534                return -1;
 535        opts->head_name = starts_with(head_name.buf, "refs/") ?
 536                xstrdup(head_name.buf) : NULL;
 537        strbuf_release(&head_name);
 538        if (get_oid(buf.buf, &oid))
 539                return error(_("could not get 'onto': '%s'"), buf.buf);
 540        opts->onto = lookup_commit_or_die(&oid, buf.buf);
 541
 542        /*
 543         * We always write to orig-head, but interactive rebase used to write to
 544         * head. Fall back to reading from head to cover for the case that the
 545         * user upgraded git with an ongoing interactive rebase.
 546         */
 547        strbuf_reset(&buf);
 548        if (file_exists(state_dir_path("orig-head", opts))) {
 549                if (read_one(state_dir_path("orig-head", opts), &buf))
 550                        return -1;
 551        } else if (read_one(state_dir_path("head", opts), &buf))
 552                return -1;
 553        if (get_oid(buf.buf, &opts->orig_head))
 554                return error(_("invalid orig-head: '%s'"), buf.buf);
 555
 556        if (file_exists(state_dir_path("quiet", opts)))
 557                opts->flags &= ~REBASE_NO_QUIET;
 558        else
 559                opts->flags |= REBASE_NO_QUIET;
 560
 561        if (file_exists(state_dir_path("verbose", opts)))
 562                opts->flags |= REBASE_VERBOSE;
 563
 564        if (file_exists(state_dir_path("signoff", opts))) {
 565                opts->signoff = 1;
 566                opts->flags |= REBASE_FORCE;
 567        }
 568
 569        if (file_exists(state_dir_path("allow_rerere_autoupdate", opts))) {
 570                strbuf_reset(&buf);
 571                if (read_one(state_dir_path("allow_rerere_autoupdate", opts),
 572                            &buf))
 573                        return -1;
 574                if (!strcmp(buf.buf, "--rerere-autoupdate"))
 575                        opts->allow_rerere_autoupdate = RERERE_AUTOUPDATE;
 576                else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
 577                        opts->allow_rerere_autoupdate = RERERE_NOAUTOUPDATE;
 578                else
 579                        warning(_("ignoring invalid allow_rerere_autoupdate: "
 580                                  "'%s'"), buf.buf);
 581        }
 582
 583        if (file_exists(state_dir_path("gpg_sign_opt", opts))) {
 584                strbuf_reset(&buf);
 585                if (read_one(state_dir_path("gpg_sign_opt", opts),
 586                            &buf))
 587                        return -1;
 588                free(opts->gpg_sign_opt);
 589                opts->gpg_sign_opt = xstrdup(buf.buf);
 590        }
 591
 592        if (file_exists(state_dir_path("strategy", opts))) {
 593                strbuf_reset(&buf);
 594                if (read_one(state_dir_path("strategy", opts), &buf))
 595                        return -1;
 596                free(opts->strategy);
 597                opts->strategy = xstrdup(buf.buf);
 598        }
 599
 600        if (file_exists(state_dir_path("strategy_opts", opts))) {
 601                strbuf_reset(&buf);
 602                if (read_one(state_dir_path("strategy_opts", opts), &buf))
 603                        return -1;
 604                free(opts->strategy_opts);
 605                opts->strategy_opts = xstrdup(buf.buf);
 606        }
 607
 608        strbuf_release(&buf);
 609
 610        return 0;
 611}
 612
 613static int rebase_write_basic_state(struct rebase_options *opts)
 614{
 615        write_file(state_dir_path("head-name", opts), "%s",
 616                   opts->head_name ? opts->head_name : "detached HEAD");
 617        write_file(state_dir_path("onto", opts), "%s",
 618                   opts->onto ? oid_to_hex(&opts->onto->object.oid) : "");
 619        write_file(state_dir_path("orig-head", opts), "%s",
 620                   oid_to_hex(&opts->orig_head));
 621        write_file(state_dir_path("quiet", opts), "%s",
 622                   opts->flags & REBASE_NO_QUIET ? "" : "t");
 623        if (opts->flags & REBASE_VERBOSE)
 624                write_file(state_dir_path("verbose", opts), "%s", "");
 625        if (opts->strategy)
 626                write_file(state_dir_path("strategy", opts), "%s",
 627                           opts->strategy);
 628        if (opts->strategy_opts)
 629                write_file(state_dir_path("strategy_opts", opts), "%s",
 630                           opts->strategy_opts);
 631        if (opts->allow_rerere_autoupdate > 0)
 632                write_file(state_dir_path("allow_rerere_autoupdate", opts),
 633                           "-%s-rerere-autoupdate",
 634                           opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE ?
 635                                "" : "-no");
 636        if (opts->gpg_sign_opt)
 637                write_file(state_dir_path("gpg_sign_opt", opts), "%s",
 638                           opts->gpg_sign_opt);
 639        if (opts->signoff)
 640                write_file(state_dir_path("strategy", opts), "--signoff");
 641
 642        return 0;
 643}
 644
 645static int apply_autostash(struct rebase_options *opts)
 646{
 647        const char *path = state_dir_path("autostash", opts);
 648        struct strbuf autostash = STRBUF_INIT;
 649        struct child_process stash_apply = CHILD_PROCESS_INIT;
 650
 651        if (!file_exists(path))
 652                return 0;
 653
 654        if (read_one(path, &autostash))
 655                return error(_("Could not read '%s'"), path);
 656        /* Ensure that the hash is not mistaken for a number */
 657        strbuf_addstr(&autostash, "^0");
 658        argv_array_pushl(&stash_apply.args,
 659                         "stash", "apply", autostash.buf, NULL);
 660        stash_apply.git_cmd = 1;
 661        stash_apply.no_stderr = stash_apply.no_stdout =
 662                stash_apply.no_stdin = 1;
 663        if (!run_command(&stash_apply))
 664                printf(_("Applied autostash.\n"));
 665        else {
 666                struct argv_array args = ARGV_ARRAY_INIT;
 667                int res = 0;
 668
 669                argv_array_pushl(&args,
 670                                 "stash", "store", "-m", "autostash", "-q",
 671                                 autostash.buf, NULL);
 672                if (run_command_v_opt(args.argv, RUN_GIT_CMD))
 673                        res = error(_("Cannot store %s"), autostash.buf);
 674                argv_array_clear(&args);
 675                strbuf_release(&autostash);
 676                if (res)
 677                        return res;
 678
 679                fprintf(stderr,
 680                        _("Applying autostash resulted in conflicts.\n"
 681                          "Your changes are safe in the stash.\n"
 682                          "You can run \"git stash pop\" or \"git stash drop\" "
 683                          "at any time.\n"));
 684        }
 685
 686        strbuf_release(&autostash);
 687        return 0;
 688}
 689
 690static int finish_rebase(struct rebase_options *opts)
 691{
 692        struct strbuf dir = STRBUF_INIT;
 693        const char *argv_gc_auto[] = { "gc", "--auto", NULL };
 694
 695        delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
 696        apply_autostash(opts);
 697        close_all_packs(the_repository->objects);
 698        /*
 699         * We ignore errors in 'gc --auto', since the
 700         * user should see them.
 701         */
 702        run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
 703        strbuf_addstr(&dir, opts->state_dir);
 704        remove_dir_recursively(&dir, 0);
 705        strbuf_release(&dir);
 706
 707        return 0;
 708}
 709
 710static struct commit *peel_committish(const char *name)
 711{
 712        struct object *obj;
 713        struct object_id oid;
 714
 715        if (get_oid(name, &oid))
 716                return NULL;
 717        obj = parse_object(the_repository, &oid);
 718        return (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
 719}
 720
 721static void add_var(struct strbuf *buf, const char *name, const char *value)
 722{
 723        if (!value)
 724                strbuf_addf(buf, "unset %s; ", name);
 725        else {
 726                strbuf_addf(buf, "%s=", name);
 727                sq_quote_buf(buf, value);
 728                strbuf_addstr(buf, "; ");
 729        }
 730}
 731
 732#define GIT_REFLOG_ACTION_ENVIRONMENT "GIT_REFLOG_ACTION"
 733
 734#define RESET_HEAD_DETACH (1<<0)
 735#define RESET_HEAD_HARD (1<<1)
 736#define RESET_HEAD_RUN_POST_CHECKOUT_HOOK (1<<2)
 737#define RESET_HEAD_REFS_ONLY (1<<3)
 738
 739static int reset_head(struct object_id *oid, const char *action,
 740                      const char *switch_to_branch, unsigned flags,
 741                      const char *reflog_orig_head, const char *reflog_head)
 742{
 743        unsigned detach_head = flags & RESET_HEAD_DETACH;
 744        unsigned reset_hard = flags & RESET_HEAD_HARD;
 745        unsigned run_hook = flags & RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
 746        unsigned refs_only = flags & RESET_HEAD_REFS_ONLY;
 747        struct object_id head_oid;
 748        struct tree_desc desc[2] = { { NULL }, { NULL } };
 749        struct lock_file lock = LOCK_INIT;
 750        struct unpack_trees_options unpack_tree_opts;
 751        struct tree *tree;
 752        const char *reflog_action;
 753        struct strbuf msg = STRBUF_INIT;
 754        size_t prefix_len;
 755        struct object_id *orig = NULL, oid_orig,
 756                *old_orig = NULL, oid_old_orig;
 757        int ret = 0, nr = 0;
 758
 759        if (switch_to_branch && !starts_with(switch_to_branch, "refs/"))
 760                BUG("Not a fully qualified branch: '%s'", switch_to_branch);
 761
 762        if (!refs_only && hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0) {
 763                ret = -1;
 764                goto leave_reset_head;
 765        }
 766
 767        if ((!oid || !reset_hard) && get_oid("HEAD", &head_oid)) {
 768                ret = error(_("could not determine HEAD revision"));
 769                goto leave_reset_head;
 770        }
 771
 772        if (!oid)
 773                oid = &head_oid;
 774
 775        if (refs_only)
 776                goto reset_head_refs;
 777
 778        memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
 779        setup_unpack_trees_porcelain(&unpack_tree_opts, action);
 780        unpack_tree_opts.head_idx = 1;
 781        unpack_tree_opts.src_index = the_repository->index;
 782        unpack_tree_opts.dst_index = the_repository->index;
 783        unpack_tree_opts.fn = reset_hard ? oneway_merge : twoway_merge;
 784        unpack_tree_opts.update = 1;
 785        unpack_tree_opts.merge = 1;
 786        if (!detach_head)
 787                unpack_tree_opts.reset = 1;
 788
 789        if (repo_read_index_unmerged(the_repository) < 0) {
 790                ret = error(_("could not read index"));
 791                goto leave_reset_head;
 792        }
 793
 794        if (!reset_hard && !fill_tree_descriptor(&desc[nr++], &head_oid)) {
 795                ret = error(_("failed to find tree of %s"),
 796                            oid_to_hex(&head_oid));
 797                goto leave_reset_head;
 798        }
 799
 800        if (!fill_tree_descriptor(&desc[nr++], oid)) {
 801                ret = error(_("failed to find tree of %s"), oid_to_hex(oid));
 802                goto leave_reset_head;
 803        }
 804
 805        if (unpack_trees(nr, desc, &unpack_tree_opts)) {
 806                ret = -1;
 807                goto leave_reset_head;
 808        }
 809
 810        tree = parse_tree_indirect(oid);
 811        prime_cache_tree(the_repository, the_repository->index, tree);
 812
 813        if (write_locked_index(the_repository->index, &lock, COMMIT_LOCK) < 0) {
 814                ret = error(_("could not write index"));
 815                goto leave_reset_head;
 816        }
 817
 818reset_head_refs:
 819        reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
 820        strbuf_addf(&msg, "%s: ", reflog_action ? reflog_action : "rebase");
 821        prefix_len = msg.len;
 822
 823        if (!get_oid("ORIG_HEAD", &oid_old_orig))
 824                old_orig = &oid_old_orig;
 825        if (!get_oid("HEAD", &oid_orig)) {
 826                orig = &oid_orig;
 827                if (!reflog_orig_head) {
 828                        strbuf_addstr(&msg, "updating ORIG_HEAD");
 829                        reflog_orig_head = msg.buf;
 830                }
 831                update_ref(reflog_orig_head, "ORIG_HEAD", orig, old_orig, 0,
 832                           UPDATE_REFS_MSG_ON_ERR);
 833        } else if (old_orig)
 834                delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
 835        if (!reflog_head) {
 836                strbuf_setlen(&msg, prefix_len);
 837                strbuf_addstr(&msg, "updating HEAD");
 838                reflog_head = msg.buf;
 839        }
 840        if (!switch_to_branch)
 841                ret = update_ref(reflog_head, "HEAD", oid, orig,
 842                                 detach_head ? REF_NO_DEREF : 0,
 843                                 UPDATE_REFS_MSG_ON_ERR);
 844        else {
 845                ret = update_ref(reflog_orig_head, switch_to_branch, oid,
 846                                 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
 847                if (!ret)
 848                        ret = create_symref("HEAD", switch_to_branch,
 849                                            reflog_head);
 850        }
 851        if (run_hook)
 852                run_hook_le(NULL, "post-checkout",
 853                            oid_to_hex(orig ? orig : &null_oid),
 854                            oid_to_hex(oid), "1", NULL);
 855
 856leave_reset_head:
 857        strbuf_release(&msg);
 858        rollback_lock_file(&lock);
 859        while (nr)
 860                free((void *)desc[--nr].buffer);
 861        return ret;
 862}
 863
 864static int move_to_original_branch(struct rebase_options *opts)
 865{
 866        struct strbuf orig_head_reflog = STRBUF_INIT, head_reflog = STRBUF_INIT;
 867        int ret;
 868
 869        if (!opts->head_name)
 870                return 0; /* nothing to move back to */
 871
 872        if (!opts->onto)
 873                BUG("move_to_original_branch without onto");
 874
 875        strbuf_addf(&orig_head_reflog, "rebase finished: %s onto %s",
 876                    opts->head_name, oid_to_hex(&opts->onto->object.oid));
 877        strbuf_addf(&head_reflog, "rebase finished: returning to %s",
 878                    opts->head_name);
 879        ret = reset_head(NULL, "", opts->head_name, RESET_HEAD_REFS_ONLY,
 880                         orig_head_reflog.buf, head_reflog.buf);
 881
 882        strbuf_release(&orig_head_reflog);
 883        strbuf_release(&head_reflog);
 884        return ret;
 885}
 886
 887static const char *resolvemsg =
 888N_("Resolve all conflicts manually, mark them as resolved with\n"
 889"\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
 890"You can instead skip this commit: run \"git rebase --skip\".\n"
 891"To abort and get back to the state before \"git rebase\", run "
 892"\"git rebase --abort\".");
 893
 894static int run_am(struct rebase_options *opts)
 895{
 896        struct child_process am = CHILD_PROCESS_INIT;
 897        struct child_process format_patch = CHILD_PROCESS_INIT;
 898        struct strbuf revisions = STRBUF_INIT;
 899        int status;
 900        char *rebased_patches;
 901
 902        am.git_cmd = 1;
 903        argv_array_push(&am.args, "am");
 904
 905        if (opts->action && !strcmp("continue", opts->action)) {
 906                argv_array_push(&am.args, "--resolved");
 907                argv_array_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
 908                if (opts->gpg_sign_opt)
 909                        argv_array_push(&am.args, opts->gpg_sign_opt);
 910                status = run_command(&am);
 911                if (status)
 912                        return status;
 913
 914                return move_to_original_branch(opts);
 915        }
 916        if (opts->action && !strcmp("skip", opts->action)) {
 917                argv_array_push(&am.args, "--skip");
 918                argv_array_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
 919                status = run_command(&am);
 920                if (status)
 921                        return status;
 922
 923                return move_to_original_branch(opts);
 924        }
 925        if (opts->action && !strcmp("show-current-patch", opts->action)) {
 926                argv_array_push(&am.args, "--show-current-patch");
 927                return run_command(&am);
 928        }
 929
 930        strbuf_addf(&revisions, "%s...%s",
 931                    oid_to_hex(opts->root ?
 932                               /* this is now equivalent to !opts->upstream */
 933                               &opts->onto->object.oid :
 934                               &opts->upstream->object.oid),
 935                    oid_to_hex(&opts->orig_head));
 936
 937        rebased_patches = xstrdup(git_path("rebased-patches"));
 938        format_patch.out = open(rebased_patches,
 939                                O_WRONLY | O_CREAT | O_TRUNC, 0666);
 940        if (format_patch.out < 0) {
 941                status = error_errno(_("could not open '%s' for writing"),
 942                                     rebased_patches);
 943                free(rebased_patches);
 944                argv_array_clear(&am.args);
 945                return status;
 946        }
 947
 948        format_patch.git_cmd = 1;
 949        argv_array_pushl(&format_patch.args, "format-patch", "-k", "--stdout",
 950                         "--full-index", "--cherry-pick", "--right-only",
 951                         "--src-prefix=a/", "--dst-prefix=b/", "--no-renames",
 952                         "--no-cover-letter", "--pretty=mboxrd", "--topo-order", NULL);
 953        if (opts->git_format_patch_opt.len)
 954                argv_array_split(&format_patch.args,
 955                                 opts->git_format_patch_opt.buf);
 956        argv_array_push(&format_patch.args, revisions.buf);
 957        if (opts->restrict_revision)
 958                argv_array_pushf(&format_patch.args, "^%s",
 959                                 oid_to_hex(&opts->restrict_revision->object.oid));
 960
 961        status = run_command(&format_patch);
 962        if (status) {
 963                unlink(rebased_patches);
 964                free(rebased_patches);
 965                argv_array_clear(&am.args);
 966
 967                reset_head(&opts->orig_head, "checkout", opts->head_name, 0,
 968                           "HEAD", NULL);
 969                error(_("\ngit encountered an error while preparing the "
 970                        "patches to replay\n"
 971                        "these revisions:\n"
 972                        "\n    %s\n\n"
 973                        "As a result, git cannot rebase them."),
 974                      opts->revisions);
 975
 976                strbuf_release(&revisions);
 977                return status;
 978        }
 979        strbuf_release(&revisions);
 980
 981        am.in = open(rebased_patches, O_RDONLY);
 982        if (am.in < 0) {
 983                status = error_errno(_("could not open '%s' for reading"),
 984                                     rebased_patches);
 985                free(rebased_patches);
 986                argv_array_clear(&am.args);
 987                return status;
 988        }
 989
 990        argv_array_pushv(&am.args, opts->git_am_opts.argv);
 991        argv_array_push(&am.args, "--rebasing");
 992        argv_array_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
 993        argv_array_push(&am.args, "--patch-format=mboxrd");
 994        if (opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE)
 995                argv_array_push(&am.args, "--rerere-autoupdate");
 996        else if (opts->allow_rerere_autoupdate == RERERE_NOAUTOUPDATE)
 997                argv_array_push(&am.args, "--no-rerere-autoupdate");
 998        if (opts->gpg_sign_opt)
 999                argv_array_push(&am.args, opts->gpg_sign_opt);
1000        status = run_command(&am);
1001        unlink(rebased_patches);
1002        free(rebased_patches);
1003
1004        if (!status) {
1005                return move_to_original_branch(opts);
1006        }
1007
1008        if (is_directory(opts->state_dir))
1009                rebase_write_basic_state(opts);
1010
1011        return status;
1012}
1013
1014static int run_specific_rebase(struct rebase_options *opts)
1015{
1016        const char *argv[] = { NULL, NULL };
1017        struct strbuf script_snippet = STRBUF_INIT, buf = STRBUF_INIT;
1018        int status;
1019        const char *backend, *backend_func;
1020
1021        if (opts->type == REBASE_INTERACTIVE) {
1022                /* Run builtin interactive rebase */
1023                struct child_process child = CHILD_PROCESS_INIT;
1024
1025                argv_array_pushf(&child.env_array, "GIT_CHERRY_PICK_HELP=%s",
1026                                 resolvemsg);
1027                if (!(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
1028                        argv_array_push(&child.env_array,
1029                                        "GIT_SEQUENCE_EDITOR=:");
1030                        opts->autosquash = 0;
1031                }
1032
1033                child.git_cmd = 1;
1034                argv_array_push(&child.args, "rebase--interactive");
1035
1036                if (opts->action)
1037                        argv_array_pushf(&child.args, "--%s", opts->action);
1038                if (opts->keep_empty)
1039                        argv_array_push(&child.args, "--keep-empty");
1040                if (opts->rebase_merges)
1041                        argv_array_push(&child.args, "--rebase-merges");
1042                if (opts->rebase_cousins)
1043                        argv_array_push(&child.args, "--rebase-cousins");
1044                if (opts->autosquash)
1045                        argv_array_push(&child.args, "--autosquash");
1046                if (opts->flags & REBASE_VERBOSE)
1047                        argv_array_push(&child.args, "--verbose");
1048                if (opts->flags & REBASE_FORCE)
1049                        argv_array_push(&child.args, "--no-ff");
1050                if (opts->restrict_revision)
1051                        argv_array_pushf(&child.args,
1052                                         "--restrict-revision=^%s",
1053                                         oid_to_hex(&opts->restrict_revision->object.oid));
1054                if (opts->upstream)
1055                        argv_array_pushf(&child.args, "--upstream=%s",
1056                                         oid_to_hex(&opts->upstream->object.oid));
1057                if (opts->onto)
1058                        argv_array_pushf(&child.args, "--onto=%s",
1059                                         oid_to_hex(&opts->onto->object.oid));
1060                if (opts->squash_onto)
1061                        argv_array_pushf(&child.args, "--squash-onto=%s",
1062                                         oid_to_hex(opts->squash_onto));
1063                if (opts->onto_name)
1064                        argv_array_pushf(&child.args, "--onto-name=%s",
1065                                         opts->onto_name);
1066                argv_array_pushf(&child.args, "--head-name=%s",
1067                                 opts->head_name ?
1068                                 opts->head_name : "detached HEAD");
1069                if (opts->strategy)
1070                        argv_array_pushf(&child.args, "--strategy=%s",
1071                                         opts->strategy);
1072                if (opts->strategy_opts)
1073                        argv_array_pushf(&child.args, "--strategy-opts=%s",
1074                                         opts->strategy_opts);
1075                if (opts->switch_to)
1076                        argv_array_pushf(&child.args, "--switch-to=%s",
1077                                         opts->switch_to);
1078                if (opts->cmd)
1079                        argv_array_pushf(&child.args, "--cmd=%s", opts->cmd);
1080                if (opts->allow_empty_message)
1081                        argv_array_push(&child.args, "--allow-empty-message");
1082                if (opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE)
1083                        argv_array_push(&child.args, "--rerere-autoupdate");
1084                else if (opts->allow_rerere_autoupdate == RERERE_NOAUTOUPDATE)
1085                        argv_array_push(&child.args, "--no-rerere-autoupdate");
1086                if (opts->gpg_sign_opt)
1087                        argv_array_push(&child.args, opts->gpg_sign_opt);
1088                if (opts->signoff)
1089                        argv_array_push(&child.args, "--signoff");
1090                if (opts->reschedule_failed_exec)
1091                        argv_array_push(&child.args, "--reschedule-failed-exec");
1092
1093                status = run_command(&child);
1094                goto finished_rebase;
1095        }
1096
1097        if (opts->type == REBASE_AM) {
1098                status = run_am(opts);
1099                goto finished_rebase;
1100        }
1101
1102        add_var(&script_snippet, "GIT_DIR", absolute_path(get_git_dir()));
1103        add_var(&script_snippet, "state_dir", opts->state_dir);
1104
1105        add_var(&script_snippet, "upstream_name", opts->upstream_name);
1106        add_var(&script_snippet, "upstream", opts->upstream ?
1107                oid_to_hex(&opts->upstream->object.oid) : NULL);
1108        add_var(&script_snippet, "head_name",
1109                opts->head_name ? opts->head_name : "detached HEAD");
1110        add_var(&script_snippet, "orig_head", oid_to_hex(&opts->orig_head));
1111        add_var(&script_snippet, "onto", opts->onto ?
1112                oid_to_hex(&opts->onto->object.oid) : NULL);
1113        add_var(&script_snippet, "onto_name", opts->onto_name);
1114        add_var(&script_snippet, "revisions", opts->revisions);
1115        add_var(&script_snippet, "restrict_revision", opts->restrict_revision ?
1116                oid_to_hex(&opts->restrict_revision->object.oid) : NULL);
1117        add_var(&script_snippet, "GIT_QUIET",
1118                opts->flags & REBASE_NO_QUIET ? "" : "t");
1119        sq_quote_argv_pretty(&buf, opts->git_am_opts.argv);
1120        add_var(&script_snippet, "git_am_opt", buf.buf);
1121        strbuf_release(&buf);
1122        add_var(&script_snippet, "verbose",
1123                opts->flags & REBASE_VERBOSE ? "t" : "");
1124        add_var(&script_snippet, "diffstat",
1125                opts->flags & REBASE_DIFFSTAT ? "t" : "");
1126        add_var(&script_snippet, "force_rebase",
1127                opts->flags & REBASE_FORCE ? "t" : "");
1128        if (opts->switch_to)
1129                add_var(&script_snippet, "switch_to", opts->switch_to);
1130        add_var(&script_snippet, "action", opts->action ? opts->action : "");
1131        add_var(&script_snippet, "signoff", opts->signoff ? "--signoff" : "");
1132        add_var(&script_snippet, "allow_rerere_autoupdate",
1133                opts->allow_rerere_autoupdate ?
1134                        opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE ?
1135                        "--rerere-autoupdate" : "--no-rerere-autoupdate" : "");
1136        add_var(&script_snippet, "keep_empty", opts->keep_empty ? "yes" : "");
1137        add_var(&script_snippet, "autosquash", opts->autosquash ? "t" : "");
1138        add_var(&script_snippet, "gpg_sign_opt", opts->gpg_sign_opt);
1139        add_var(&script_snippet, "cmd", opts->cmd);
1140        add_var(&script_snippet, "allow_empty_message",
1141                opts->allow_empty_message ?  "--allow-empty-message" : "");
1142        add_var(&script_snippet, "rebase_merges",
1143                opts->rebase_merges ? "t" : "");
1144        add_var(&script_snippet, "rebase_cousins",
1145                opts->rebase_cousins ? "t" : "");
1146        add_var(&script_snippet, "strategy", opts->strategy);
1147        add_var(&script_snippet, "strategy_opts", opts->strategy_opts);
1148        add_var(&script_snippet, "rebase_root", opts->root ? "t" : "");
1149        add_var(&script_snippet, "squash_onto",
1150                opts->squash_onto ? oid_to_hex(opts->squash_onto) : "");
1151        add_var(&script_snippet, "git_format_patch_opt",
1152                opts->git_format_patch_opt.buf);
1153
1154        if (is_interactive(opts) &&
1155            !(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
1156                strbuf_addstr(&script_snippet,
1157                              "GIT_SEQUENCE_EDITOR=:; export GIT_SEQUENCE_EDITOR; ");
1158                opts->autosquash = 0;
1159        }
1160
1161        switch (opts->type) {
1162        case REBASE_AM:
1163                backend = "git-rebase--am";
1164                backend_func = "git_rebase__am";
1165                break;
1166        case REBASE_PRESERVE_MERGES:
1167                backend = "git-rebase--preserve-merges";
1168                backend_func = "git_rebase__preserve_merges";
1169                break;
1170        default:
1171                BUG("Unhandled rebase type %d", opts->type);
1172                break;
1173        }
1174
1175        strbuf_addf(&script_snippet,
1176                    ". git-sh-setup && . git-rebase--common &&"
1177                    " . %s && %s", backend, backend_func);
1178        argv[0] = script_snippet.buf;
1179
1180        status = run_command_v_opt(argv, RUN_USING_SHELL);
1181finished_rebase:
1182        if (opts->dont_finish_rebase)
1183                ; /* do nothing */
1184        else if (opts->type == REBASE_INTERACTIVE)
1185                ; /* interactive rebase cleans up after itself */
1186        else if (status == 0) {
1187                if (!file_exists(state_dir_path("stopped-sha", opts)))
1188                        finish_rebase(opts);
1189        } else if (status == 2) {
1190                struct strbuf dir = STRBUF_INIT;
1191
1192                apply_autostash(opts);
1193                strbuf_addstr(&dir, opts->state_dir);
1194                remove_dir_recursively(&dir, 0);
1195                strbuf_release(&dir);
1196                die("Nothing to do");
1197        }
1198
1199        strbuf_release(&script_snippet);
1200
1201        return status ? -1 : 0;
1202}
1203
1204static int rebase_config(const char *var, const char *value, void *data)
1205{
1206        struct rebase_options *opts = data;
1207
1208        if (!strcmp(var, "rebase.stat")) {
1209                if (git_config_bool(var, value))
1210                        opts->flags |= REBASE_DIFFSTAT;
1211                else
1212                        opts->flags &= !REBASE_DIFFSTAT;
1213                return 0;
1214        }
1215
1216        if (!strcmp(var, "rebase.autosquash")) {
1217                opts->autosquash = git_config_bool(var, value);
1218                return 0;
1219        }
1220
1221        if (!strcmp(var, "commit.gpgsign")) {
1222                free(opts->gpg_sign_opt);
1223                opts->gpg_sign_opt = git_config_bool(var, value) ?
1224                        xstrdup("-S") : NULL;
1225                return 0;
1226        }
1227
1228        if (!strcmp(var, "rebase.autostash")) {
1229                opts->autostash = git_config_bool(var, value);
1230                return 0;
1231        }
1232
1233        if (!strcmp(var, "rebase.reschedulefailedexec")) {
1234                opts->reschedule_failed_exec = git_config_bool(var, value);
1235                return 0;
1236        }
1237
1238        return git_default_config(var, value, data);
1239}
1240
1241/*
1242 * Determines whether the commits in from..to are linear, i.e. contain
1243 * no merge commits. This function *expects* `from` to be an ancestor of
1244 * `to`.
1245 */
1246static int is_linear_history(struct commit *from, struct commit *to)
1247{
1248        while (to && to != from) {
1249                parse_commit(to);
1250                if (!to->parents)
1251                        return 1;
1252                if (to->parents->next)
1253                        return 0;
1254                to = to->parents->item;
1255        }
1256        return 1;
1257}
1258
1259static int can_fast_forward(struct commit *onto, struct object_id *head_oid,
1260                            struct object_id *merge_base)
1261{
1262        struct commit *head = lookup_commit(the_repository, head_oid);
1263        struct commit_list *merge_bases;
1264        int res;
1265
1266        if (!head)
1267                return 0;
1268
1269        merge_bases = get_merge_bases(onto, head);
1270        if (merge_bases && !merge_bases->next) {
1271                oidcpy(merge_base, &merge_bases->item->object.oid);
1272                res = oideq(merge_base, &onto->object.oid);
1273        } else {
1274                oidcpy(merge_base, &null_oid);
1275                res = 0;
1276        }
1277        free_commit_list(merge_bases);
1278        return res && is_linear_history(onto, head);
1279}
1280
1281/* -i followed by -m is still -i */
1282static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
1283{
1284        struct rebase_options *opts = opt->value;
1285
1286        BUG_ON_OPT_NEG(unset);
1287        BUG_ON_OPT_ARG(arg);
1288
1289        if (!is_interactive(opts))
1290                opts->type = REBASE_MERGE;
1291
1292        return 0;
1293}
1294
1295/* -i followed by -p is still explicitly interactive, but -p alone is not */
1296static int parse_opt_interactive(const struct option *opt, const char *arg,
1297                                 int unset)
1298{
1299        struct rebase_options *opts = opt->value;
1300
1301        BUG_ON_OPT_NEG(unset);
1302        BUG_ON_OPT_ARG(arg);
1303
1304        opts->type = REBASE_INTERACTIVE;
1305        opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
1306
1307        return 0;
1308}
1309
1310static void NORETURN error_on_missing_default_upstream(void)
1311{
1312        struct branch *current_branch = branch_get(NULL);
1313
1314        printf(_("%s\n"
1315                 "Please specify which branch you want to rebase against.\n"
1316                 "See git-rebase(1) for details.\n"
1317                 "\n"
1318                 "    git rebase '<branch>'\n"
1319                 "\n"),
1320                current_branch ? _("There is no tracking information for "
1321                        "the current branch.") :
1322                        _("You are not currently on a branch."));
1323
1324        if (current_branch) {
1325                const char *remote = current_branch->remote_name;
1326
1327                if (!remote)
1328                        remote = _("<remote>");
1329
1330                printf(_("If you wish to set tracking information for this "
1331                         "branch you can do so with:\n"
1332                         "\n"
1333                         "    git branch --set-upstream-to=%s/<branch> %s\n"
1334                         "\n"),
1335                       remote, current_branch->name);
1336        }
1337        exit(1);
1338}
1339
1340static void set_reflog_action(struct rebase_options *options)
1341{
1342        const char *env;
1343        struct strbuf buf = STRBUF_INIT;
1344
1345        if (!is_interactive(options))
1346                return;
1347
1348        env = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
1349        if (env && strcmp("rebase", env))
1350                return; /* only override it if it is "rebase" */
1351
1352        strbuf_addf(&buf, "rebase -i (%s)", options->action);
1353        setenv(GIT_REFLOG_ACTION_ENVIRONMENT, buf.buf, 1);
1354        strbuf_release(&buf);
1355}
1356
1357static int check_exec_cmd(const char *cmd)
1358{
1359        if (strchr(cmd, '\n'))
1360                return error(_("exec commands cannot contain newlines"));
1361
1362        /* Does the command consist purely of whitespace? */
1363        if (!cmd[strspn(cmd, " \t\r\f\v")])
1364                return error(_("empty exec command"));
1365
1366        return 0;
1367}
1368
1369
1370int cmd_rebase(int argc, const char **argv, const char *prefix)
1371{
1372        struct rebase_options options = {
1373                .type = REBASE_UNSPECIFIED,
1374                .flags = REBASE_NO_QUIET,
1375                .git_am_opts = ARGV_ARRAY_INIT,
1376                .allow_empty_message = 1,
1377                .git_format_patch_opt = STRBUF_INIT,
1378        };
1379        const char *branch_name;
1380        int ret, flags, total_argc, in_progress = 0;
1381        int ok_to_skip_pre_rebase = 0;
1382        struct strbuf msg = STRBUF_INIT;
1383        struct strbuf revisions = STRBUF_INIT;
1384        struct strbuf buf = STRBUF_INIT;
1385        struct object_id merge_base;
1386        enum {
1387                NO_ACTION,
1388                ACTION_CONTINUE,
1389                ACTION_SKIP,
1390                ACTION_ABORT,
1391                ACTION_QUIT,
1392                ACTION_EDIT_TODO,
1393                ACTION_SHOW_CURRENT_PATCH,
1394        } action = NO_ACTION;
1395        static const char *action_names[] = { "undefined",
1396                                              "continue",
1397                                              "skip",
1398                                              "abort",
1399                                              "quit",
1400                                              "edit_todo",
1401                                              "show_current_patch" };
1402        const char *gpg_sign = NULL;
1403        struct string_list exec = STRING_LIST_INIT_NODUP;
1404        const char *rebase_merges = NULL;
1405        int fork_point = -1;
1406        struct string_list strategy_options = STRING_LIST_INIT_NODUP;
1407        struct object_id squash_onto;
1408        char *squash_onto_name = NULL;
1409        struct option builtin_rebase_options[] = {
1410                OPT_STRING(0, "onto", &options.onto_name,
1411                           N_("revision"),
1412                           N_("rebase onto given branch instead of upstream")),
1413                OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
1414                         N_("allow pre-rebase hook to run")),
1415                OPT_NEGBIT('q', "quiet", &options.flags,
1416                           N_("be quiet. implies --no-stat"),
1417                           REBASE_NO_QUIET| REBASE_VERBOSE | REBASE_DIFFSTAT),
1418                OPT_BIT('v', "verbose", &options.flags,
1419                        N_("display a diffstat of what changed upstream"),
1420                        REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1421                {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
1422                        N_("do not show diffstat of what changed upstream"),
1423                        PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
1424                OPT_BOOL(0, "signoff", &options.signoff,
1425                         N_("add a Signed-off-by: line to each commit")),
1426                OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &options.git_am_opts,
1427                                  NULL, N_("passed to 'git am'"),
1428                                  PARSE_OPT_NOARG),
1429                OPT_PASSTHRU_ARGV(0, "committer-date-is-author-date",
1430                                  &options.git_am_opts, NULL,
1431                                  N_("passed to 'git am'"), PARSE_OPT_NOARG),
1432                OPT_PASSTHRU_ARGV(0, "ignore-date", &options.git_am_opts, NULL,
1433                                  N_("passed to 'git am'"), PARSE_OPT_NOARG),
1434                OPT_PASSTHRU_ARGV('C', NULL, &options.git_am_opts, N_("n"),
1435                                  N_("passed to 'git apply'"), 0),
1436                OPT_PASSTHRU_ARGV(0, "whitespace", &options.git_am_opts,
1437                                  N_("action"), N_("passed to 'git apply'"), 0),
1438                OPT_BIT('f', "force-rebase", &options.flags,
1439                        N_("cherry-pick all commits, even if unchanged"),
1440                        REBASE_FORCE),
1441                OPT_BIT(0, "no-ff", &options.flags,
1442                        N_("cherry-pick all commits, even if unchanged"),
1443                        REBASE_FORCE),
1444                OPT_CMDMODE(0, "continue", &action, N_("continue"),
1445                            ACTION_CONTINUE),
1446                OPT_CMDMODE(0, "skip", &action,
1447                            N_("skip current patch and continue"), ACTION_SKIP),
1448                OPT_CMDMODE(0, "abort", &action,
1449                            N_("abort and check out the original branch"),
1450                            ACTION_ABORT),
1451                OPT_CMDMODE(0, "quit", &action,
1452                            N_("abort but keep HEAD where it is"), ACTION_QUIT),
1453                OPT_CMDMODE(0, "edit-todo", &action, N_("edit the todo list "
1454                            "during an interactive rebase"), ACTION_EDIT_TODO),
1455                OPT_CMDMODE(0, "show-current-patch", &action,
1456                            N_("show the patch file being applied or merged"),
1457                            ACTION_SHOW_CURRENT_PATCH),
1458                { OPTION_CALLBACK, 'm', "merge", &options, NULL,
1459                        N_("use merging strategies to rebase"),
1460                        PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1461                        parse_opt_merge },
1462                { OPTION_CALLBACK, 'i', "interactive", &options, NULL,
1463                        N_("let the user edit the list of commits to rebase"),
1464                        PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1465                        parse_opt_interactive },
1466                OPT_SET_INT('p', "preserve-merges", &options.type,
1467                            N_("try to recreate merges instead of ignoring "
1468                               "them"), REBASE_PRESERVE_MERGES),
1469                OPT_RERERE_AUTOUPDATE(&options.allow_rerere_autoupdate),
1470                OPT_BOOL('k', "keep-empty", &options.keep_empty,
1471                         N_("preserve empty commits during rebase")),
1472                OPT_BOOL(0, "autosquash", &options.autosquash,
1473                         N_("move commits that begin with "
1474                            "squash!/fixup! under -i")),
1475                { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
1476                        N_("GPG-sign commits"),
1477                        PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1478                OPT_BOOL(0, "autostash", &options.autostash,
1479                         N_("automatically stash/stash pop before and after")),
1480                OPT_STRING_LIST('x', "exec", &exec, N_("exec"),
1481                                N_("add exec lines after each commit of the "
1482                                   "editable list")),
1483                OPT_BOOL(0, "allow-empty-message",
1484                         &options.allow_empty_message,
1485                         N_("allow rebasing commits with empty messages")),
1486                {OPTION_STRING, 'r', "rebase-merges", &rebase_merges,
1487                        N_("mode"),
1488                        N_("try to rebase merges instead of skipping them"),
1489                        PARSE_OPT_OPTARG, NULL, (intptr_t)""},
1490                OPT_BOOL(0, "fork-point", &fork_point,
1491                         N_("use 'merge-base --fork-point' to refine upstream")),
1492                OPT_STRING('s', "strategy", &options.strategy,
1493                           N_("strategy"), N_("use the given merge strategy")),
1494                OPT_STRING_LIST('X', "strategy-option", &strategy_options,
1495                                N_("option"),
1496                                N_("pass the argument through to the merge "
1497                                   "strategy")),
1498                OPT_BOOL(0, "root", &options.root,
1499                         N_("rebase all reachable commits up to the root(s)")),
1500                OPT_BOOL(0, "reschedule-failed-exec",
1501                         &options.reschedule_failed_exec,
1502                         N_("automatically re-schedule any `exec` that fails")),
1503                OPT_END(),
1504        };
1505        int i;
1506
1507        /*
1508         * NEEDSWORK: Once the builtin rebase has been tested enough
1509         * and git-legacy-rebase.sh is retired to contrib/, this preamble
1510         * can be removed.
1511         */
1512
1513        if (!use_builtin_rebase()) {
1514                const char *path = mkpath("%s/git-legacy-rebase",
1515                                          git_exec_path());
1516
1517                if (sane_execvp(path, (char **)argv) < 0)
1518                        die_errno(_("could not exec %s"), path);
1519                else
1520                        BUG("sane_execvp() returned???");
1521        }
1522
1523        if (argc == 2 && !strcmp(argv[1], "-h"))
1524                usage_with_options(builtin_rebase_usage,
1525                                   builtin_rebase_options);
1526
1527        prefix = setup_git_directory();
1528        trace_repo_setup(prefix);
1529        setup_work_tree();
1530
1531        git_config(rebase_config, &options);
1532
1533        strbuf_reset(&buf);
1534        strbuf_addf(&buf, "%s/applying", apply_dir());
1535        if(file_exists(buf.buf))
1536                die(_("It looks like 'git am' is in progress. Cannot rebase."));
1537
1538        if (is_directory(apply_dir())) {
1539                options.type = REBASE_AM;
1540                options.state_dir = apply_dir();
1541        } else if (is_directory(merge_dir())) {
1542                strbuf_reset(&buf);
1543                strbuf_addf(&buf, "%s/rewritten", merge_dir());
1544                if (is_directory(buf.buf)) {
1545                        options.type = REBASE_PRESERVE_MERGES;
1546                        options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1547                } else {
1548                        strbuf_reset(&buf);
1549                        strbuf_addf(&buf, "%s/interactive", merge_dir());
1550                        if(file_exists(buf.buf)) {
1551                                options.type = REBASE_INTERACTIVE;
1552                                options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1553                        } else
1554                                options.type = REBASE_MERGE;
1555                }
1556                options.state_dir = merge_dir();
1557        }
1558
1559        if (options.type != REBASE_UNSPECIFIED)
1560                in_progress = 1;
1561
1562        total_argc = argc;
1563        argc = parse_options(argc, argv, prefix,
1564                             builtin_rebase_options,
1565                             builtin_rebase_usage, 0);
1566
1567        if (action != NO_ACTION && total_argc != 2) {
1568                usage_with_options(builtin_rebase_usage,
1569                                   builtin_rebase_options);
1570        }
1571
1572        if (argc > 2)
1573                usage_with_options(builtin_rebase_usage,
1574                                   builtin_rebase_options);
1575
1576        if (action != NO_ACTION && !in_progress)
1577                die(_("No rebase in progress?"));
1578        setenv(GIT_REFLOG_ACTION_ENVIRONMENT, "rebase", 0);
1579
1580        if (action == ACTION_EDIT_TODO && !is_interactive(&options))
1581                die(_("The --edit-todo action can only be used during "
1582                      "interactive rebase."));
1583
1584        if (trace2_is_enabled()) {
1585                if (is_interactive(&options))
1586                        trace2_cmd_mode("interactive");
1587                else if (exec.nr)
1588                        trace2_cmd_mode("interactive-exec");
1589                else
1590                        trace2_cmd_mode(action_names[action]);
1591        }
1592
1593        switch (action) {
1594        case ACTION_CONTINUE: {
1595                struct object_id head;
1596                struct lock_file lock_file = LOCK_INIT;
1597                int fd;
1598
1599                options.action = "continue";
1600                set_reflog_action(&options);
1601
1602                /* Sanity check */
1603                if (get_oid("HEAD", &head))
1604                        die(_("Cannot read HEAD"));
1605
1606                fd = hold_locked_index(&lock_file, 0);
1607                if (repo_read_index(the_repository) < 0)
1608                        die(_("could not read index"));
1609                refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
1610                              NULL);
1611                if (0 <= fd)
1612                        repo_update_index_if_able(the_repository, &lock_file);
1613                rollback_lock_file(&lock_file);
1614
1615                if (has_unstaged_changes(the_repository, 1)) {
1616                        puts(_("You must edit all merge conflicts and then\n"
1617                               "mark them as resolved using git add"));
1618                        exit(1);
1619                }
1620                if (read_basic_state(&options))
1621                        exit(1);
1622                goto run_rebase;
1623        }
1624        case ACTION_SKIP: {
1625                struct string_list merge_rr = STRING_LIST_INIT_DUP;
1626
1627                options.action = "skip";
1628                set_reflog_action(&options);
1629
1630                rerere_clear(the_repository, &merge_rr);
1631                string_list_clear(&merge_rr, 1);
1632
1633                if (reset_head(NULL, "reset", NULL, RESET_HEAD_HARD,
1634                               NULL, NULL) < 0)
1635                        die(_("could not discard worktree changes"));
1636                remove_branch_state(the_repository);
1637                if (read_basic_state(&options))
1638                        exit(1);
1639                goto run_rebase;
1640        }
1641        case ACTION_ABORT: {
1642                struct string_list merge_rr = STRING_LIST_INIT_DUP;
1643                options.action = "abort";
1644                set_reflog_action(&options);
1645
1646                rerere_clear(the_repository, &merge_rr);
1647                string_list_clear(&merge_rr, 1);
1648
1649                if (read_basic_state(&options))
1650                        exit(1);
1651                if (reset_head(&options.orig_head, "reset",
1652                               options.head_name, RESET_HEAD_HARD,
1653                               NULL, NULL) < 0)
1654                        die(_("could not move back to %s"),
1655                            oid_to_hex(&options.orig_head));
1656                remove_branch_state(the_repository);
1657                ret = finish_rebase(&options);
1658                goto cleanup;
1659        }
1660        case ACTION_QUIT: {
1661                strbuf_reset(&buf);
1662                strbuf_addstr(&buf, options.state_dir);
1663                ret = !!remove_dir_recursively(&buf, 0);
1664                if (ret)
1665                        die(_("could not remove '%s'"), options.state_dir);
1666                goto cleanup;
1667        }
1668        case ACTION_EDIT_TODO:
1669                options.action = "edit-todo";
1670                options.dont_finish_rebase = 1;
1671                goto run_rebase;
1672        case ACTION_SHOW_CURRENT_PATCH:
1673                options.action = "show-current-patch";
1674                options.dont_finish_rebase = 1;
1675                goto run_rebase;
1676        case NO_ACTION:
1677                break;
1678        default:
1679                BUG("action: %d", action);
1680        }
1681
1682        /* Make sure no rebase is in progress */
1683        if (in_progress) {
1684                const char *last_slash = strrchr(options.state_dir, '/');
1685                const char *state_dir_base =
1686                        last_slash ? last_slash + 1 : options.state_dir;
1687                const char *cmd_live_rebase =
1688                        "git rebase (--continue | --abort | --skip)";
1689                strbuf_reset(&buf);
1690                strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
1691                die(_("It seems that there is already a %s directory, and\n"
1692                      "I wonder if you are in the middle of another rebase.  "
1693                      "If that is the\n"
1694                      "case, please try\n\t%s\n"
1695                      "If that is not the case, please\n\t%s\n"
1696                      "and run me again.  I am stopping in case you still "
1697                      "have something\n"
1698                      "valuable there.\n"),
1699                    state_dir_base, cmd_live_rebase, buf.buf);
1700        }
1701
1702        for (i = 0; i < options.git_am_opts.argc; i++) {
1703                const char *option = options.git_am_opts.argv[i], *p;
1704                if (!strcmp(option, "--committer-date-is-author-date") ||
1705                    !strcmp(option, "--ignore-date") ||
1706                    !strcmp(option, "--whitespace=fix") ||
1707                    !strcmp(option, "--whitespace=strip"))
1708                        options.flags |= REBASE_FORCE;
1709                else if (skip_prefix(option, "-C", &p)) {
1710                        while (*p)
1711                                if (!isdigit(*(p++)))
1712                                        die(_("switch `C' expects a "
1713                                              "numerical value"));
1714                } else if (skip_prefix(option, "--whitespace=", &p)) {
1715                        if (*p && strcmp(p, "warn") && strcmp(p, "nowarn") &&
1716                            strcmp(p, "error") && strcmp(p, "error-all"))
1717                                die("Invalid whitespace option: '%s'", p);
1718                }
1719        }
1720
1721        for (i = 0; i < exec.nr; i++)
1722                if (check_exec_cmd(exec.items[i].string))
1723                        exit(1);
1724
1725        if (!(options.flags & REBASE_NO_QUIET))
1726                argv_array_push(&options.git_am_opts, "-q");
1727
1728        if (options.keep_empty)
1729                imply_interactive(&options, "--keep-empty");
1730
1731        if (gpg_sign) {
1732                free(options.gpg_sign_opt);
1733                options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
1734        }
1735
1736        if (exec.nr) {
1737                int i;
1738
1739                imply_interactive(&options, "--exec");
1740
1741                strbuf_reset(&buf);
1742                for (i = 0; i < exec.nr; i++)
1743                        strbuf_addf(&buf, "exec %s\n", exec.items[i].string);
1744                options.cmd = xstrdup(buf.buf);
1745        }
1746
1747        if (rebase_merges) {
1748                if (!*rebase_merges)
1749                        ; /* default mode; do nothing */
1750                else if (!strcmp("rebase-cousins", rebase_merges))
1751                        options.rebase_cousins = 1;
1752                else if (strcmp("no-rebase-cousins", rebase_merges))
1753                        die(_("Unknown mode: %s"), rebase_merges);
1754                options.rebase_merges = 1;
1755                imply_interactive(&options, "--rebase-merges");
1756        }
1757
1758        if (strategy_options.nr) {
1759                int i;
1760
1761                if (!options.strategy)
1762                        options.strategy = "recursive";
1763
1764                strbuf_reset(&buf);
1765                for (i = 0; i < strategy_options.nr; i++)
1766                        strbuf_addf(&buf, " --%s",
1767                                    strategy_options.items[i].string);
1768                options.strategy_opts = xstrdup(buf.buf);
1769        }
1770
1771        if (options.strategy) {
1772                options.strategy = xstrdup(options.strategy);
1773                switch (options.type) {
1774                case REBASE_AM:
1775                        die(_("--strategy requires --merge or --interactive"));
1776                case REBASE_MERGE:
1777                case REBASE_INTERACTIVE:
1778                case REBASE_PRESERVE_MERGES:
1779                        /* compatible */
1780                        break;
1781                case REBASE_UNSPECIFIED:
1782                        options.type = REBASE_MERGE;
1783                        break;
1784                default:
1785                        BUG("unhandled rebase type (%d)", options.type);
1786                }
1787        }
1788
1789        if (options.type == REBASE_MERGE)
1790                imply_interactive(&options, "--merge");
1791
1792        if (options.root && !options.onto_name)
1793                imply_interactive(&options, "--root without --onto");
1794
1795        if (isatty(2) && options.flags & REBASE_NO_QUIET)
1796                strbuf_addstr(&options.git_format_patch_opt, " --progress");
1797
1798        switch (options.type) {
1799        case REBASE_MERGE:
1800        case REBASE_INTERACTIVE:
1801        case REBASE_PRESERVE_MERGES:
1802                options.state_dir = merge_dir();
1803                break;
1804        case REBASE_AM:
1805                options.state_dir = apply_dir();
1806                break;
1807        default:
1808                /* the default rebase backend is `--am` */
1809                options.type = REBASE_AM;
1810                options.state_dir = apply_dir();
1811                break;
1812        }
1813
1814        if (options.reschedule_failed_exec && !is_interactive(&options))
1815                die(_("%s requires an interactive rebase"), "--reschedule-failed-exec");
1816
1817        if (options.git_am_opts.argc) {
1818                /* all am options except -q are compatible only with --am */
1819                for (i = options.git_am_opts.argc - 1; i >= 0; i--)
1820                        if (strcmp(options.git_am_opts.argv[i], "-q"))
1821                                break;
1822
1823                if (is_interactive(&options) && i >= 0)
1824                        die(_("cannot combine am options with either "
1825                              "interactive or merge options"));
1826        }
1827
1828        if (options.signoff) {
1829                if (options.type == REBASE_PRESERVE_MERGES)
1830                        die("cannot combine '--signoff' with "
1831                            "'--preserve-merges'");
1832                argv_array_push(&options.git_am_opts, "--signoff");
1833                options.flags |= REBASE_FORCE;
1834        }
1835
1836        if (options.type == REBASE_PRESERVE_MERGES) {
1837                /*
1838                 * Note: incompatibility with --signoff handled in signoff block above
1839                 * Note: incompatibility with --interactive is just a strong warning;
1840                 *       git-rebase.txt caveats with "unless you know what you are doing"
1841                 */
1842                if (options.rebase_merges)
1843                        die(_("cannot combine '--preserve-merges' with "
1844                              "'--rebase-merges'"));
1845
1846                if (options.reschedule_failed_exec)
1847                        die(_("error: cannot combine '--preserve-merges' with "
1848                              "'--reschedule-failed-exec'"));
1849        }
1850
1851        if (options.rebase_merges) {
1852                if (strategy_options.nr)
1853                        die(_("cannot combine '--rebase-merges' with "
1854                              "'--strategy-option'"));
1855                if (options.strategy)
1856                        die(_("cannot combine '--rebase-merges' with "
1857                              "'--strategy'"));
1858        }
1859
1860        if (!options.root) {
1861                if (argc < 1) {
1862                        struct branch *branch;
1863
1864                        branch = branch_get(NULL);
1865                        options.upstream_name = branch_get_upstream(branch,
1866                                                                    NULL);
1867                        if (!options.upstream_name)
1868                                error_on_missing_default_upstream();
1869                        if (fork_point < 0)
1870                                fork_point = 1;
1871                } else {
1872                        options.upstream_name = argv[0];
1873                        argc--;
1874                        argv++;
1875                        if (!strcmp(options.upstream_name, "-"))
1876                                options.upstream_name = "@{-1}";
1877                }
1878                options.upstream = peel_committish(options.upstream_name);
1879                if (!options.upstream)
1880                        die(_("invalid upstream '%s'"), options.upstream_name);
1881                options.upstream_arg = options.upstream_name;
1882        } else {
1883                if (!options.onto_name) {
1884                        if (commit_tree("", 0, the_hash_algo->empty_tree, NULL,
1885                                        &squash_onto, NULL, NULL) < 0)
1886                                die(_("Could not create new root commit"));
1887                        options.squash_onto = &squash_onto;
1888                        options.onto_name = squash_onto_name =
1889                                xstrdup(oid_to_hex(&squash_onto));
1890                }
1891                options.upstream_name = NULL;
1892                options.upstream = NULL;
1893                if (argc > 1)
1894                        usage_with_options(builtin_rebase_usage,
1895                                           builtin_rebase_options);
1896                options.upstream_arg = "--root";
1897        }
1898
1899        /* Make sure the branch to rebase onto is valid. */
1900        if (!options.onto_name)
1901                options.onto_name = options.upstream_name;
1902        if (strstr(options.onto_name, "...")) {
1903                if (get_oid_mb(options.onto_name, &merge_base) < 0)
1904                        die(_("'%s': need exactly one merge base"),
1905                            options.onto_name);
1906                options.onto = lookup_commit_or_die(&merge_base,
1907                                                    options.onto_name);
1908        } else {
1909                options.onto = peel_committish(options.onto_name);
1910                if (!options.onto)
1911                        die(_("Does not point to a valid commit '%s'"),
1912                                options.onto_name);
1913        }
1914
1915        /*
1916         * If the branch to rebase is given, that is the branch we will rebase
1917         * branch_name -- branch/commit being rebased, or
1918         *                HEAD (already detached)
1919         * orig_head -- commit object name of tip of the branch before rebasing
1920         * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
1921         */
1922        if (argc == 1) {
1923                /* Is it "rebase other branchname" or "rebase other commit"? */
1924                branch_name = argv[0];
1925                options.switch_to = argv[0];
1926
1927                /* Is it a local branch? */
1928                strbuf_reset(&buf);
1929                strbuf_addf(&buf, "refs/heads/%s", branch_name);
1930                if (!read_ref(buf.buf, &options.orig_head))
1931                        options.head_name = xstrdup(buf.buf);
1932                /* If not is it a valid ref (branch or commit)? */
1933                else if (!get_oid(branch_name, &options.orig_head))
1934                        options.head_name = NULL;
1935                else
1936                        die(_("fatal: no such branch/commit '%s'"),
1937                            branch_name);
1938        } else if (argc == 0) {
1939                /* Do not need to switch branches, we are already on it. */
1940                options.head_name =
1941                        xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
1942                                         &flags));
1943                if (!options.head_name)
1944                        die(_("No such ref: %s"), "HEAD");
1945                if (flags & REF_ISSYMREF) {
1946                        if (!skip_prefix(options.head_name,
1947                                         "refs/heads/", &branch_name))
1948                                branch_name = options.head_name;
1949
1950                } else {
1951                        free(options.head_name);
1952                        options.head_name = NULL;
1953                        branch_name = "HEAD";
1954                }
1955                if (get_oid("HEAD", &options.orig_head))
1956                        die(_("Could not resolve HEAD to a revision"));
1957        } else
1958                BUG("unexpected number of arguments left to parse");
1959
1960        if (fork_point > 0) {
1961                struct commit *head =
1962                        lookup_commit_reference(the_repository,
1963                                                &options.orig_head);
1964                options.restrict_revision =
1965                        get_fork_point(options.upstream_name, head);
1966        }
1967
1968        if (repo_read_index(the_repository) < 0)
1969                die(_("could not read index"));
1970
1971        if (options.autostash) {
1972                struct lock_file lock_file = LOCK_INIT;
1973                int fd;
1974
1975                fd = hold_locked_index(&lock_file, 0);
1976                refresh_cache(REFRESH_QUIET);
1977                if (0 <= fd)
1978                        repo_update_index_if_able(the_repository, &lock_file);
1979                rollback_lock_file(&lock_file);
1980
1981                if (has_unstaged_changes(the_repository, 1) ||
1982                    has_uncommitted_changes(the_repository, 1)) {
1983                        const char *autostash =
1984                                state_dir_path("autostash", &options);
1985                        struct child_process stash = CHILD_PROCESS_INIT;
1986                        struct object_id oid;
1987                        struct commit *head =
1988                                lookup_commit_reference(the_repository,
1989                                                        &options.orig_head);
1990
1991                        argv_array_pushl(&stash.args,
1992                                         "stash", "create", "autostash", NULL);
1993                        stash.git_cmd = 1;
1994                        stash.no_stdin = 1;
1995                        strbuf_reset(&buf);
1996                        if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
1997                                die(_("Cannot autostash"));
1998                        strbuf_trim_trailing_newline(&buf);
1999                        if (get_oid(buf.buf, &oid))
2000                                die(_("Unexpected stash response: '%s'"),
2001                                    buf.buf);
2002                        strbuf_reset(&buf);
2003                        strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
2004
2005                        if (safe_create_leading_directories_const(autostash))
2006                                die(_("Could not create directory for '%s'"),
2007                                    options.state_dir);
2008                        write_file(autostash, "%s", oid_to_hex(&oid));
2009                        printf(_("Created autostash: %s\n"), buf.buf);
2010                        if (reset_head(&head->object.oid, "reset --hard",
2011                                       NULL, RESET_HEAD_HARD, NULL, NULL) < 0)
2012                                die(_("could not reset --hard"));
2013                        printf(_("HEAD is now at %s"),
2014                               find_unique_abbrev(&head->object.oid,
2015                                                  DEFAULT_ABBREV));
2016                        strbuf_reset(&buf);
2017                        pp_commit_easy(CMIT_FMT_ONELINE, head, &buf);
2018                        if (buf.len > 0)
2019                                printf(" %s", buf.buf);
2020                        putchar('\n');
2021
2022                        if (discard_index(the_repository->index) < 0 ||
2023                                repo_read_index(the_repository) < 0)
2024                                die(_("could not read index"));
2025                }
2026        }
2027
2028        if (require_clean_work_tree(the_repository, "rebase",
2029                                    _("Please commit or stash them."), 1, 1)) {
2030                ret = 1;
2031                goto cleanup;
2032        }
2033
2034        /*
2035         * Now we are rebasing commits upstream..orig_head (or with --root,
2036         * everything leading up to orig_head) on top of onto.
2037         */
2038
2039        /*
2040         * Check if we are already based on onto with linear history,
2041         * but this should be done only when upstream and onto are the same
2042         * and if this is not an interactive rebase.
2043         */
2044        if (can_fast_forward(options.onto, &options.orig_head, &merge_base) &&
2045            !is_interactive(&options) && !options.restrict_revision &&
2046            options.upstream &&
2047            !oidcmp(&options.upstream->object.oid, &options.onto->object.oid)) {
2048                int flag;
2049
2050                if (!(options.flags & REBASE_FORCE)) {
2051                        /* Lazily switch to the target branch if needed... */
2052                        if (options.switch_to) {
2053                                struct object_id oid;
2054
2055                                if (get_oid(options.switch_to, &oid) < 0) {
2056                                        ret = !!error(_("could not parse '%s'"),
2057                                                      options.switch_to);
2058                                        goto cleanup;
2059                                }
2060
2061                                strbuf_reset(&buf);
2062                                strbuf_addf(&buf, "%s: checkout %s",
2063                                            getenv(GIT_REFLOG_ACTION_ENVIRONMENT),
2064                                            options.switch_to);
2065                                if (reset_head(&oid, "checkout",
2066                                               options.head_name,
2067                                               RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
2068                                               NULL, buf.buf) < 0) {
2069                                        ret = !!error(_("could not switch to "
2070                                                        "%s"),
2071                                                      options.switch_to);
2072                                        goto cleanup;
2073                                }
2074                        }
2075
2076                        if (!(options.flags & REBASE_NO_QUIET))
2077                                ; /* be quiet */
2078                        else if (!strcmp(branch_name, "HEAD") &&
2079                                 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
2080                                puts(_("HEAD is up to date."));
2081                        else
2082                                printf(_("Current branch %s is up to date.\n"),
2083                                       branch_name);
2084                        ret = !!finish_rebase(&options);
2085                        goto cleanup;
2086                } else if (!(options.flags & REBASE_NO_QUIET))
2087                        ; /* be quiet */
2088                else if (!strcmp(branch_name, "HEAD") &&
2089                         resolve_ref_unsafe("HEAD", 0, NULL, &flag))
2090                        puts(_("HEAD is up to date, rebase forced."));
2091                else
2092                        printf(_("Current branch %s is up to date, rebase "
2093                                 "forced.\n"), branch_name);
2094        }
2095
2096        /* If a hook exists, give it a chance to interrupt*/
2097        if (!ok_to_skip_pre_rebase &&
2098            run_hook_le(NULL, "pre-rebase", options.upstream_arg,
2099                        argc ? argv[0] : NULL, NULL))
2100                die(_("The pre-rebase hook refused to rebase."));
2101
2102        if (options.flags & REBASE_DIFFSTAT) {
2103                struct diff_options opts;
2104
2105                if (options.flags & REBASE_VERBOSE) {
2106                        if (is_null_oid(&merge_base))
2107                                printf(_("Changes to %s:\n"),
2108                                       oid_to_hex(&options.onto->object.oid));
2109                        else
2110                                printf(_("Changes from %s to %s:\n"),
2111                                       oid_to_hex(&merge_base),
2112                                       oid_to_hex(&options.onto->object.oid));
2113                }
2114
2115                /* We want color (if set), but no pager */
2116                diff_setup(&opts);
2117                opts.stat_width = -1; /* use full terminal width */
2118                opts.stat_graph_width = -1; /* respect statGraphWidth config */
2119                opts.output_format |=
2120                        DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
2121                opts.detect_rename = DIFF_DETECT_RENAME;
2122                diff_setup_done(&opts);
2123                diff_tree_oid(is_null_oid(&merge_base) ?
2124                              the_hash_algo->empty_tree : &merge_base,
2125                              &options.onto->object.oid, "", &opts);
2126                diffcore_std(&opts);
2127                diff_flush(&opts);
2128        }
2129
2130        if (is_interactive(&options))
2131                goto run_rebase;
2132
2133        /* Detach HEAD and reset the tree */
2134        if (options.flags & REBASE_NO_QUIET)
2135                printf(_("First, rewinding head to replay your work on top of "
2136                         "it...\n"));
2137
2138        strbuf_addf(&msg, "%s: checkout %s",
2139                    getenv(GIT_REFLOG_ACTION_ENVIRONMENT), options.onto_name);
2140        if (reset_head(&options.onto->object.oid, "checkout", NULL,
2141                       RESET_HEAD_DETACH | RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
2142                       NULL, msg.buf))
2143                die(_("Could not detach HEAD"));
2144        strbuf_release(&msg);
2145
2146        /*
2147         * If the onto is a proper descendant of the tip of the branch, then
2148         * we just fast-forwarded.
2149         */
2150        strbuf_reset(&msg);
2151        if (!oidcmp(&merge_base, &options.orig_head)) {
2152                printf(_("Fast-forwarded %s to %s.\n"),
2153                        branch_name, options.onto_name);
2154                strbuf_addf(&msg, "rebase finished: %s onto %s",
2155                        options.head_name ? options.head_name : "detached HEAD",
2156                        oid_to_hex(&options.onto->object.oid));
2157                reset_head(NULL, "Fast-forwarded", options.head_name, 0,
2158                           "HEAD", msg.buf);
2159                strbuf_release(&msg);
2160                ret = !!finish_rebase(&options);
2161                goto cleanup;
2162        }
2163
2164        strbuf_addf(&revisions, "%s..%s",
2165                    options.root ? oid_to_hex(&options.onto->object.oid) :
2166                    (options.restrict_revision ?
2167                     oid_to_hex(&options.restrict_revision->object.oid) :
2168                     oid_to_hex(&options.upstream->object.oid)),
2169                    oid_to_hex(&options.orig_head));
2170
2171        options.revisions = revisions.buf;
2172
2173run_rebase:
2174        ret = !!run_specific_rebase(&options);
2175
2176cleanup:
2177        strbuf_release(&revisions);
2178        free(options.head_name);
2179        free(options.gpg_sign_opt);
2180        free(options.cmd);
2181        free(squash_onto_name);
2182        return ret;
2183}