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