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