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