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