builtin / rebase.con commit Merge branch 'az/instaweb-py3-http-server' (abf39e3)
   1/*
   2 * "git rebase" builtin command
   3 *
   4 * Copyright (c) 2018 Pratik Karki
   5 */
   6
   7#include "builtin.h"
   8#include "run-command.h"
   9#include "exec-cmd.h"
  10#include "argv-array.h"
  11#include "dir.h"
  12#include "packfile.h"
  13#include "refs.h"
  14#include "quote.h"
  15#include "config.h"
  16#include "cache-tree.h"
  17#include "unpack-trees.h"
  18#include "lockfile.h"
  19#include "parse-options.h"
  20#include "commit.h"
  21#include "diff.h"
  22#include "wt-status.h"
  23#include "revision.h"
  24#include "commit-reach.h"
  25#include "rerere.h"
  26#include "branch.h"
  27
  28static char const * const builtin_rebase_usage[] = {
  29        N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
  30                "[<upstream>] [<branch>]"),
  31        N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
  32                "--root [<branch>]"),
  33        N_("git rebase --continue | --abort | --skip | --edit-todo"),
  34        NULL
  35};
  36
  37static GIT_PATH_FUNC(apply_dir, "rebase-apply")
  38static GIT_PATH_FUNC(merge_dir, "rebase-merge")
  39
  40enum rebase_type {
  41        REBASE_UNSPECIFIED = -1,
  42        REBASE_AM,
  43        REBASE_MERGE,
  44        REBASE_INTERACTIVE,
  45        REBASE_PRESERVE_MERGES
  46};
  47
  48static int use_builtin_rebase(void)
  49{
  50        struct child_process cp = CHILD_PROCESS_INIT;
  51        struct strbuf out = STRBUF_INIT;
  52        int ret, env = git_env_bool("GIT_TEST_REBASE_USE_BUILTIN", -1);
  53
  54        if (env != -1)
  55                return env;
  56
  57        argv_array_pushl(&cp.args,
  58                         "config", "--bool", "rebase.usebuiltin", NULL);
  59        cp.git_cmd = 1;
  60        if (capture_command(&cp, &out, 6)) {
  61                strbuf_release(&out);
  62                return 1;
  63        }
  64
  65        strbuf_trim(&out);
  66        ret = !strcmp("true", out.buf);
  67        strbuf_release(&out);
  68        return ret;
  69}
  70
  71struct rebase_options {
  72        enum rebase_type type;
  73        const char *state_dir;
  74        struct commit *upstream;
  75        const char *upstream_name;
  76        const char *upstream_arg;
  77        char *head_name;
  78        struct object_id orig_head;
  79        struct commit *onto;
  80        const char *onto_name;
  81        const char *revisions;
  82        const char *switch_to;
  83        int root;
  84        struct object_id *squash_onto;
  85        struct commit *restrict_revision;
  86        int dont_finish_rebase;
  87        enum {
  88                REBASE_NO_QUIET = 1<<0,
  89                REBASE_VERBOSE = 1<<1,
  90                REBASE_DIFFSTAT = 1<<2,
  91                REBASE_FORCE = 1<<3,
  92                REBASE_INTERACTIVE_EXPLICIT = 1<<4,
  93        } flags;
  94        struct argv_array git_am_opts;
  95        const char *action;
  96        int signoff;
  97        int allow_rerere_autoupdate;
  98        int keep_empty;
  99        int autosquash;
 100        char *gpg_sign_opt;
 101        int autostash;
 102        char *cmd;
 103        int allow_empty_message;
 104        int rebase_merges, rebase_cousins;
 105        char *strategy, *strategy_opts;
 106        struct strbuf git_format_patch_opt;
 107        int reschedule_failed_exec;
 108};
 109
 110static int is_interactive(struct rebase_options *opts)
 111{
 112        return opts->type == REBASE_INTERACTIVE ||
 113                opts->type == REBASE_PRESERVE_MERGES;
 114}
 115
 116static void imply_interactive(struct rebase_options *opts, const char *option)
 117{
 118        switch (opts->type) {
 119        case REBASE_AM:
 120                die(_("%s requires an interactive rebase"), option);
 121                break;
 122        case REBASE_INTERACTIVE:
 123        case REBASE_PRESERVE_MERGES:
 124                break;
 125        case REBASE_MERGE:
 126                /* we silently *upgrade* --merge to --interactive if needed */
 127        default:
 128                opts->type = REBASE_INTERACTIVE; /* implied */
 129                break;
 130        }
 131}
 132
 133/* Returns the filename prefixed by the state_dir */
 134static const char *state_dir_path(const char *filename, struct rebase_options *opts)
 135{
 136        static struct strbuf path = STRBUF_INIT;
 137        static size_t prefix_len;
 138
 139        if (!prefix_len) {
 140                strbuf_addf(&path, "%s/", opts->state_dir);
 141                prefix_len = path.len;
 142        }
 143
 144        strbuf_setlen(&path, prefix_len);
 145        strbuf_addstr(&path, filename);
 146        return path.buf;
 147}
 148
 149/* Read one file, then strip line endings */
 150static int read_one(const char *path, struct strbuf *buf)
 151{
 152        if (strbuf_read_file(buf, path, 0) < 0)
 153                return error_errno(_("could not read '%s'"), path);
 154        strbuf_trim_trailing_newline(buf);
 155        return 0;
 156}
 157
 158/* Initialize the rebase options from the state directory. */
 159static int read_basic_state(struct rebase_options *opts)
 160{
 161        struct strbuf head_name = STRBUF_INIT;
 162        struct strbuf buf = STRBUF_INIT;
 163        struct object_id oid;
 164
 165        if (read_one(state_dir_path("head-name", opts), &head_name) ||
 166            read_one(state_dir_path("onto", opts), &buf))
 167                return -1;
 168        opts->head_name = starts_with(head_name.buf, "refs/") ?
 169                xstrdup(head_name.buf) : NULL;
 170        strbuf_release(&head_name);
 171        if (get_oid(buf.buf, &oid))
 172                return error(_("could not get 'onto': '%s'"), buf.buf);
 173        opts->onto = lookup_commit_or_die(&oid, buf.buf);
 174
 175        /*
 176         * We always write to orig-head, but interactive rebase used to write to
 177         * head. Fall back to reading from head to cover for the case that the
 178         * user upgraded git with an ongoing interactive rebase.
 179         */
 180        strbuf_reset(&buf);
 181        if (file_exists(state_dir_path("orig-head", opts))) {
 182                if (read_one(state_dir_path("orig-head", opts), &buf))
 183                        return -1;
 184        } else if (read_one(state_dir_path("head", opts), &buf))
 185                return -1;
 186        if (get_oid(buf.buf, &opts->orig_head))
 187                return error(_("invalid orig-head: '%s'"), buf.buf);
 188
 189        strbuf_reset(&buf);
 190        if (read_one(state_dir_path("quiet", opts), &buf))
 191                return -1;
 192        if (buf.len)
 193                opts->flags &= ~REBASE_NO_QUIET;
 194        else
 195                opts->flags |= REBASE_NO_QUIET;
 196
 197        if (file_exists(state_dir_path("verbose", opts)))
 198                opts->flags |= REBASE_VERBOSE;
 199
 200        if (file_exists(state_dir_path("signoff", opts))) {
 201                opts->signoff = 1;
 202                opts->flags |= REBASE_FORCE;
 203        }
 204
 205        if (file_exists(state_dir_path("allow_rerere_autoupdate", opts))) {
 206                strbuf_reset(&buf);
 207                if (read_one(state_dir_path("allow_rerere_autoupdate", opts),
 208                            &buf))
 209                        return -1;
 210                if (!strcmp(buf.buf, "--rerere-autoupdate"))
 211                        opts->allow_rerere_autoupdate = 1;
 212                else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
 213                        opts->allow_rerere_autoupdate = 0;
 214                else
 215                        warning(_("ignoring invalid allow_rerere_autoupdate: "
 216                                  "'%s'"), buf.buf);
 217        } else
 218                opts->allow_rerere_autoupdate = -1;
 219
 220        if (file_exists(state_dir_path("gpg_sign_opt", opts))) {
 221                strbuf_reset(&buf);
 222                if (read_one(state_dir_path("gpg_sign_opt", opts),
 223                            &buf))
 224                        return -1;
 225                free(opts->gpg_sign_opt);
 226                opts->gpg_sign_opt = xstrdup(buf.buf);
 227        }
 228
 229        if (file_exists(state_dir_path("strategy", opts))) {
 230                strbuf_reset(&buf);
 231                if (read_one(state_dir_path("strategy", opts), &buf))
 232                        return -1;
 233                free(opts->strategy);
 234                opts->strategy = xstrdup(buf.buf);
 235        }
 236
 237        if (file_exists(state_dir_path("strategy_opts", opts))) {
 238                strbuf_reset(&buf);
 239                if (read_one(state_dir_path("strategy_opts", opts), &buf))
 240                        return -1;
 241                free(opts->strategy_opts);
 242                opts->strategy_opts = xstrdup(buf.buf);
 243        }
 244
 245        strbuf_release(&buf);
 246
 247        return 0;
 248}
 249
 250static int apply_autostash(struct rebase_options *opts)
 251{
 252        const char *path = state_dir_path("autostash", opts);
 253        struct strbuf autostash = STRBUF_INIT;
 254        struct child_process stash_apply = CHILD_PROCESS_INIT;
 255
 256        if (!file_exists(path))
 257                return 0;
 258
 259        if (read_one(path, &autostash))
 260                return error(_("Could not read '%s'"), path);
 261        /* Ensure that the hash is not mistaken for a number */
 262        strbuf_addstr(&autostash, "^0");
 263        argv_array_pushl(&stash_apply.args,
 264                         "stash", "apply", autostash.buf, NULL);
 265        stash_apply.git_cmd = 1;
 266        stash_apply.no_stderr = stash_apply.no_stdout =
 267                stash_apply.no_stdin = 1;
 268        if (!run_command(&stash_apply))
 269                printf(_("Applied autostash.\n"));
 270        else {
 271                struct argv_array args = ARGV_ARRAY_INIT;
 272                int res = 0;
 273
 274                argv_array_pushl(&args,
 275                                 "stash", "store", "-m", "autostash", "-q",
 276                                 autostash.buf, NULL);
 277                if (run_command_v_opt(args.argv, RUN_GIT_CMD))
 278                        res = error(_("Cannot store %s"), autostash.buf);
 279                argv_array_clear(&args);
 280                strbuf_release(&autostash);
 281                if (res)
 282                        return res;
 283
 284                fprintf(stderr,
 285                        _("Applying autostash resulted in conflicts.\n"
 286                          "Your changes are safe in the stash.\n"
 287                          "You can run \"git stash pop\" or \"git stash drop\" "
 288                          "at any time.\n"));
 289        }
 290
 291        strbuf_release(&autostash);
 292        return 0;
 293}
 294
 295static int finish_rebase(struct rebase_options *opts)
 296{
 297        struct strbuf dir = STRBUF_INIT;
 298        const char *argv_gc_auto[] = { "gc", "--auto", NULL };
 299
 300        delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
 301        apply_autostash(opts);
 302        close_all_packs(the_repository->objects);
 303        /*
 304         * We ignore errors in 'gc --auto', since the
 305         * user should see them.
 306         */
 307        run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
 308        strbuf_addstr(&dir, opts->state_dir);
 309        remove_dir_recursively(&dir, 0);
 310        strbuf_release(&dir);
 311
 312        return 0;
 313}
 314
 315static struct commit *peel_committish(const char *name)
 316{
 317        struct object *obj;
 318        struct object_id oid;
 319
 320        if (get_oid(name, &oid))
 321                return NULL;
 322        obj = parse_object(the_repository, &oid);
 323        return (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
 324}
 325
 326static void add_var(struct strbuf *buf, const char *name, const char *value)
 327{
 328        if (!value)
 329                strbuf_addf(buf, "unset %s; ", name);
 330        else {
 331                strbuf_addf(buf, "%s=", name);
 332                sq_quote_buf(buf, value);
 333                strbuf_addstr(buf, "; ");
 334        }
 335}
 336
 337static const char *resolvemsg =
 338N_("Resolve all conflicts manually, mark them as resolved with\n"
 339"\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
 340"You can instead skip this commit: run \"git rebase --skip\".\n"
 341"To abort and get back to the state before \"git rebase\", run "
 342"\"git rebase --abort\".");
 343
 344static int run_specific_rebase(struct rebase_options *opts)
 345{
 346        const char *argv[] = { NULL, NULL };
 347        struct strbuf script_snippet = STRBUF_INIT, buf = STRBUF_INIT;
 348        int status;
 349        const char *backend, *backend_func;
 350
 351        if (opts->type == REBASE_INTERACTIVE) {
 352                /* Run builtin interactive rebase */
 353                struct child_process child = CHILD_PROCESS_INIT;
 354
 355                argv_array_pushf(&child.env_array, "GIT_CHERRY_PICK_HELP=%s",
 356                                 resolvemsg);
 357                if (!(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
 358                        argv_array_push(&child.env_array,
 359                                        "GIT_SEQUENCE_EDITOR=:");
 360                        opts->autosquash = 0;
 361                }
 362
 363                child.git_cmd = 1;
 364                argv_array_push(&child.args, "rebase--interactive");
 365
 366                if (opts->action)
 367                        argv_array_pushf(&child.args, "--%s", opts->action);
 368                if (opts->keep_empty)
 369                        argv_array_push(&child.args, "--keep-empty");
 370                if (opts->rebase_merges)
 371                        argv_array_push(&child.args, "--rebase-merges");
 372                if (opts->rebase_cousins)
 373                        argv_array_push(&child.args, "--rebase-cousins");
 374                if (opts->autosquash)
 375                        argv_array_push(&child.args, "--autosquash");
 376                if (opts->flags & REBASE_VERBOSE)
 377                        argv_array_push(&child.args, "--verbose");
 378                if (opts->flags & REBASE_FORCE)
 379                        argv_array_push(&child.args, "--no-ff");
 380                if (opts->restrict_revision)
 381                        argv_array_pushf(&child.args,
 382                                         "--restrict-revision=^%s",
 383                                         oid_to_hex(&opts->restrict_revision->object.oid));
 384                if (opts->upstream)
 385                        argv_array_pushf(&child.args, "--upstream=%s",
 386                                         oid_to_hex(&opts->upstream->object.oid));
 387                if (opts->onto)
 388                        argv_array_pushf(&child.args, "--onto=%s",
 389                                         oid_to_hex(&opts->onto->object.oid));
 390                if (opts->squash_onto)
 391                        argv_array_pushf(&child.args, "--squash-onto=%s",
 392                                         oid_to_hex(opts->squash_onto));
 393                if (opts->onto_name)
 394                        argv_array_pushf(&child.args, "--onto-name=%s",
 395                                         opts->onto_name);
 396                argv_array_pushf(&child.args, "--head-name=%s",
 397                                 opts->head_name ?
 398                                 opts->head_name : "detached HEAD");
 399                if (opts->strategy)
 400                        argv_array_pushf(&child.args, "--strategy=%s",
 401                                         opts->strategy);
 402                if (opts->strategy_opts)
 403                        argv_array_pushf(&child.args, "--strategy-opts=%s",
 404                                         opts->strategy_opts);
 405                if (opts->switch_to)
 406                        argv_array_pushf(&child.args, "--switch-to=%s",
 407                                         opts->switch_to);
 408                if (opts->cmd)
 409                        argv_array_pushf(&child.args, "--cmd=%s", opts->cmd);
 410                if (opts->allow_empty_message)
 411                        argv_array_push(&child.args, "--allow-empty-message");
 412                if (opts->allow_rerere_autoupdate > 0)
 413                        argv_array_push(&child.args, "--rerere-autoupdate");
 414                else if (opts->allow_rerere_autoupdate == 0)
 415                        argv_array_push(&child.args, "--no-rerere-autoupdate");
 416                if (opts->gpg_sign_opt)
 417                        argv_array_push(&child.args, opts->gpg_sign_opt);
 418                if (opts->signoff)
 419                        argv_array_push(&child.args, "--signoff");
 420                if (opts->reschedule_failed_exec)
 421                        argv_array_push(&child.args, "--reschedule-failed-exec");
 422
 423                status = run_command(&child);
 424                goto finished_rebase;
 425        }
 426
 427        add_var(&script_snippet, "GIT_DIR", absolute_path(get_git_dir()));
 428        add_var(&script_snippet, "state_dir", opts->state_dir);
 429
 430        add_var(&script_snippet, "upstream_name", opts->upstream_name);
 431        add_var(&script_snippet, "upstream", opts->upstream ?
 432                oid_to_hex(&opts->upstream->object.oid) : NULL);
 433        add_var(&script_snippet, "head_name",
 434                opts->head_name ? opts->head_name : "detached HEAD");
 435        add_var(&script_snippet, "orig_head", oid_to_hex(&opts->orig_head));
 436        add_var(&script_snippet, "onto", opts->onto ?
 437                oid_to_hex(&opts->onto->object.oid) : NULL);
 438        add_var(&script_snippet, "onto_name", opts->onto_name);
 439        add_var(&script_snippet, "revisions", opts->revisions);
 440        add_var(&script_snippet, "restrict_revision", opts->restrict_revision ?
 441                oid_to_hex(&opts->restrict_revision->object.oid) : NULL);
 442        add_var(&script_snippet, "GIT_QUIET",
 443                opts->flags & REBASE_NO_QUIET ? "" : "t");
 444        sq_quote_argv_pretty(&buf, opts->git_am_opts.argv);
 445        add_var(&script_snippet, "git_am_opt", buf.buf);
 446        strbuf_release(&buf);
 447        add_var(&script_snippet, "verbose",
 448                opts->flags & REBASE_VERBOSE ? "t" : "");
 449        add_var(&script_snippet, "diffstat",
 450                opts->flags & REBASE_DIFFSTAT ? "t" : "");
 451        add_var(&script_snippet, "force_rebase",
 452                opts->flags & REBASE_FORCE ? "t" : "");
 453        if (opts->switch_to)
 454                add_var(&script_snippet, "switch_to", opts->switch_to);
 455        add_var(&script_snippet, "action", opts->action ? opts->action : "");
 456        add_var(&script_snippet, "signoff", opts->signoff ? "--signoff" : "");
 457        add_var(&script_snippet, "allow_rerere_autoupdate",
 458                opts->allow_rerere_autoupdate < 0 ? "" :
 459                opts->allow_rerere_autoupdate ?
 460                "--rerere-autoupdate" : "--no-rerere-autoupdate");
 461        add_var(&script_snippet, "keep_empty", opts->keep_empty ? "yes" : "");
 462        add_var(&script_snippet, "autosquash", opts->autosquash ? "t" : "");
 463        add_var(&script_snippet, "gpg_sign_opt", opts->gpg_sign_opt);
 464        add_var(&script_snippet, "cmd", opts->cmd);
 465        add_var(&script_snippet, "allow_empty_message",
 466                opts->allow_empty_message ?  "--allow-empty-message" : "");
 467        add_var(&script_snippet, "rebase_merges",
 468                opts->rebase_merges ? "t" : "");
 469        add_var(&script_snippet, "rebase_cousins",
 470                opts->rebase_cousins ? "t" : "");
 471        add_var(&script_snippet, "strategy", opts->strategy);
 472        add_var(&script_snippet, "strategy_opts", opts->strategy_opts);
 473        add_var(&script_snippet, "rebase_root", opts->root ? "t" : "");
 474        add_var(&script_snippet, "squash_onto",
 475                opts->squash_onto ? oid_to_hex(opts->squash_onto) : "");
 476        add_var(&script_snippet, "git_format_patch_opt",
 477                opts->git_format_patch_opt.buf);
 478
 479        if (is_interactive(opts) &&
 480            !(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
 481                strbuf_addstr(&script_snippet,
 482                              "GIT_SEQUENCE_EDITOR=:; export GIT_SEQUENCE_EDITOR; ");
 483                opts->autosquash = 0;
 484        }
 485
 486        switch (opts->type) {
 487        case REBASE_AM:
 488                backend = "git-rebase--am";
 489                backend_func = "git_rebase__am";
 490                break;
 491        case REBASE_MERGE:
 492                backend = "git-rebase--merge";
 493                backend_func = "git_rebase__merge";
 494                break;
 495        case REBASE_PRESERVE_MERGES:
 496                backend = "git-rebase--preserve-merges";
 497                backend_func = "git_rebase__preserve_merges";
 498                break;
 499        default:
 500                BUG("Unhandled rebase type %d", opts->type);
 501                break;
 502        }
 503
 504        strbuf_addf(&script_snippet,
 505                    ". git-sh-setup && . git-rebase--common &&"
 506                    " . %s && %s", backend, backend_func);
 507        argv[0] = script_snippet.buf;
 508
 509        status = run_command_v_opt(argv, RUN_USING_SHELL);
 510finished_rebase:
 511        if (opts->dont_finish_rebase)
 512                ; /* do nothing */
 513        else if (opts->type == REBASE_INTERACTIVE)
 514                ; /* interactive rebase cleans up after itself */
 515        else if (status == 0) {
 516                if (!file_exists(state_dir_path("stopped-sha", opts)))
 517                        finish_rebase(opts);
 518        } else if (status == 2) {
 519                struct strbuf dir = STRBUF_INIT;
 520
 521                apply_autostash(opts);
 522                strbuf_addstr(&dir, opts->state_dir);
 523                remove_dir_recursively(&dir, 0);
 524                strbuf_release(&dir);
 525                die("Nothing to do");
 526        }
 527
 528        strbuf_release(&script_snippet);
 529
 530        return status ? -1 : 0;
 531}
 532
 533#define GIT_REFLOG_ACTION_ENVIRONMENT "GIT_REFLOG_ACTION"
 534
 535#define RESET_HEAD_DETACH (1<<0)
 536#define RESET_HEAD_HARD (1<<1)
 537#define RESET_HEAD_RUN_POST_CHECKOUT_HOOK (1<<2)
 538
 539static int reset_head(struct object_id *oid, const char *action,
 540                      const char *switch_to_branch, unsigned flags,
 541                      const char *reflog_orig_head, const char *reflog_head)
 542{
 543        unsigned detach_head = flags & RESET_HEAD_DETACH;
 544        unsigned reset_hard = flags & RESET_HEAD_HARD;
 545        unsigned run_hook = flags & RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
 546        struct object_id head_oid;
 547        struct tree_desc desc[2] = { { NULL }, { NULL } };
 548        struct lock_file lock = LOCK_INIT;
 549        struct unpack_trees_options unpack_tree_opts;
 550        struct tree *tree;
 551        const char *reflog_action;
 552        struct strbuf msg = STRBUF_INIT;
 553        size_t prefix_len;
 554        struct object_id *orig = NULL, oid_orig,
 555                *old_orig = NULL, oid_old_orig;
 556        int ret = 0, nr = 0;
 557
 558        if (switch_to_branch && !starts_with(switch_to_branch, "refs/"))
 559                BUG("Not a fully qualified branch: '%s'", switch_to_branch);
 560
 561        if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0) {
 562                ret = -1;
 563                goto leave_reset_head;
 564        }
 565
 566        if ((!oid || !reset_hard) && get_oid("HEAD", &head_oid)) {
 567                ret = error(_("could not determine HEAD revision"));
 568                goto leave_reset_head;
 569        }
 570
 571        if (!oid)
 572                oid = &head_oid;
 573
 574        memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
 575        setup_unpack_trees_porcelain(&unpack_tree_opts, action);
 576        unpack_tree_opts.head_idx = 1;
 577        unpack_tree_opts.src_index = the_repository->index;
 578        unpack_tree_opts.dst_index = the_repository->index;
 579        unpack_tree_opts.fn = reset_hard ? oneway_merge : twoway_merge;
 580        unpack_tree_opts.update = 1;
 581        unpack_tree_opts.merge = 1;
 582        if (!detach_head)
 583                unpack_tree_opts.reset = 1;
 584
 585        if (read_index_unmerged(the_repository->index) < 0) {
 586                ret = error(_("could not read index"));
 587                goto leave_reset_head;
 588        }
 589
 590        if (!reset_hard && !fill_tree_descriptor(&desc[nr++], &head_oid)) {
 591                ret = error(_("failed to find tree of %s"),
 592                            oid_to_hex(&head_oid));
 593                goto leave_reset_head;
 594        }
 595
 596        if (!fill_tree_descriptor(&desc[nr++], oid)) {
 597                ret = error(_("failed to find tree of %s"), oid_to_hex(oid));
 598                goto leave_reset_head;
 599        }
 600
 601        if (unpack_trees(nr, desc, &unpack_tree_opts)) {
 602                ret = -1;
 603                goto leave_reset_head;
 604        }
 605
 606        tree = parse_tree_indirect(oid);
 607        prime_cache_tree(the_repository, the_repository->index, tree);
 608
 609        if (write_locked_index(the_repository->index, &lock, COMMIT_LOCK) < 0) {
 610                ret = error(_("could not write index"));
 611                goto leave_reset_head;
 612        }
 613
 614        reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
 615        strbuf_addf(&msg, "%s: ", reflog_action ? reflog_action : "rebase");
 616        prefix_len = msg.len;
 617
 618        if (!get_oid("ORIG_HEAD", &oid_old_orig))
 619                old_orig = &oid_old_orig;
 620        if (!get_oid("HEAD", &oid_orig)) {
 621                orig = &oid_orig;
 622                if (!reflog_orig_head) {
 623                        strbuf_addstr(&msg, "updating ORIG_HEAD");
 624                        reflog_orig_head = msg.buf;
 625                }
 626                update_ref(reflog_orig_head, "ORIG_HEAD", orig, old_orig, 0,
 627                           UPDATE_REFS_MSG_ON_ERR);
 628        } else if (old_orig)
 629                delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
 630        if (!reflog_head) {
 631                strbuf_setlen(&msg, prefix_len);
 632                strbuf_addstr(&msg, "updating HEAD");
 633                reflog_head = msg.buf;
 634        }
 635        if (!switch_to_branch)
 636                ret = update_ref(reflog_head, "HEAD", oid, orig,
 637                                 detach_head ? REF_NO_DEREF : 0,
 638                                 UPDATE_REFS_MSG_ON_ERR);
 639        else {
 640                ret = create_symref("HEAD", switch_to_branch, msg.buf);
 641                if (!ret)
 642                        ret = update_ref(reflog_head, "HEAD", oid, NULL, 0,
 643                                         UPDATE_REFS_MSG_ON_ERR);
 644        }
 645        if (run_hook)
 646                run_hook_le(NULL, "post-checkout",
 647                            oid_to_hex(orig ? orig : &null_oid),
 648                            oid_to_hex(oid), "1", NULL);
 649
 650leave_reset_head:
 651        strbuf_release(&msg);
 652        rollback_lock_file(&lock);
 653        while (nr)
 654                free((void *)desc[--nr].buffer);
 655        return ret;
 656}
 657
 658static int rebase_config(const char *var, const char *value, void *data)
 659{
 660        struct rebase_options *opts = data;
 661
 662        if (!strcmp(var, "rebase.stat")) {
 663                if (git_config_bool(var, value))
 664                        opts->flags |= REBASE_DIFFSTAT;
 665                else
 666                        opts->flags &= !REBASE_DIFFSTAT;
 667                return 0;
 668        }
 669
 670        if (!strcmp(var, "rebase.autosquash")) {
 671                opts->autosquash = git_config_bool(var, value);
 672                return 0;
 673        }
 674
 675        if (!strcmp(var, "commit.gpgsign")) {
 676                free(opts->gpg_sign_opt);
 677                opts->gpg_sign_opt = git_config_bool(var, value) ?
 678                        xstrdup("-S") : NULL;
 679                return 0;
 680        }
 681
 682        if (!strcmp(var, "rebase.autostash")) {
 683                opts->autostash = git_config_bool(var, value);
 684                return 0;
 685        }
 686
 687        if (!strcmp(var, "rebase.reschedulefailedexec")) {
 688                opts->reschedule_failed_exec = git_config_bool(var, value);
 689                return 0;
 690        }
 691
 692        return git_default_config(var, value, data);
 693}
 694
 695/*
 696 * Determines whether the commits in from..to are linear, i.e. contain
 697 * no merge commits. This function *expects* `from` to be an ancestor of
 698 * `to`.
 699 */
 700static int is_linear_history(struct commit *from, struct commit *to)
 701{
 702        while (to && to != from) {
 703                parse_commit(to);
 704                if (!to->parents)
 705                        return 1;
 706                if (to->parents->next)
 707                        return 0;
 708                to = to->parents->item;
 709        }
 710        return 1;
 711}
 712
 713static int can_fast_forward(struct commit *onto, struct object_id *head_oid,
 714                            struct object_id *merge_base)
 715{
 716        struct commit *head = lookup_commit(the_repository, head_oid);
 717        struct commit_list *merge_bases;
 718        int res;
 719
 720        if (!head)
 721                return 0;
 722
 723        merge_bases = get_merge_bases(onto, head);
 724        if (merge_bases && !merge_bases->next) {
 725                oidcpy(merge_base, &merge_bases->item->object.oid);
 726                res = oideq(merge_base, &onto->object.oid);
 727        } else {
 728                oidcpy(merge_base, &null_oid);
 729                res = 0;
 730        }
 731        free_commit_list(merge_bases);
 732        return res && is_linear_history(onto, head);
 733}
 734
 735/* -i followed by -m is still -i */
 736static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
 737{
 738        struct rebase_options *opts = opt->value;
 739
 740        BUG_ON_OPT_NEG(unset);
 741        BUG_ON_OPT_ARG(arg);
 742
 743        if (!is_interactive(opts))
 744                opts->type = REBASE_MERGE;
 745
 746        return 0;
 747}
 748
 749/* -i followed by -p is still explicitly interactive, but -p alone is not */
 750static int parse_opt_interactive(const struct option *opt, const char *arg,
 751                                 int unset)
 752{
 753        struct rebase_options *opts = opt->value;
 754
 755        BUG_ON_OPT_NEG(unset);
 756        BUG_ON_OPT_ARG(arg);
 757
 758        opts->type = REBASE_INTERACTIVE;
 759        opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
 760
 761        return 0;
 762}
 763
 764struct opt_y {
 765        struct string_list *list;
 766        struct rebase_options *options;
 767};
 768
 769static int parse_opt_y(const struct option *opt, const char *arg, int unset)
 770{
 771        struct opt_y *o = opt->value;
 772
 773        if (unset || !arg)
 774                return -1;
 775
 776        o->options->reschedule_failed_exec = 1;
 777        string_list_append(o->list, arg);
 778        return 0;
 779}
 780
 781static void NORETURN error_on_missing_default_upstream(void)
 782{
 783        struct branch *current_branch = branch_get(NULL);
 784
 785        printf(_("%s\n"
 786                 "Please specify which branch you want to rebase against.\n"
 787                 "See git-rebase(1) for details.\n"
 788                 "\n"
 789                 "    git rebase '<branch>'\n"
 790                 "\n"),
 791                current_branch ? _("There is no tracking information for "
 792                        "the current branch.") :
 793                        _("You are not currently on a branch."));
 794
 795        if (current_branch) {
 796                const char *remote = current_branch->remote_name;
 797
 798                if (!remote)
 799                        remote = _("<remote>");
 800
 801                printf(_("If you wish to set tracking information for this "
 802                         "branch you can do so with:\n"
 803                         "\n"
 804                         "    git branch --set-upstream-to=%s/<branch> %s\n"
 805                         "\n"),
 806                       remote, current_branch->name);
 807        }
 808        exit(1);
 809}
 810
 811static void set_reflog_action(struct rebase_options *options)
 812{
 813        const char *env;
 814        struct strbuf buf = STRBUF_INIT;
 815
 816        if (!is_interactive(options))
 817                return;
 818
 819        env = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
 820        if (env && strcmp("rebase", env))
 821                return; /* only override it if it is "rebase" */
 822
 823        strbuf_addf(&buf, "rebase -i (%s)", options->action);
 824        setenv(GIT_REFLOG_ACTION_ENVIRONMENT, buf.buf, 1);
 825        strbuf_release(&buf);
 826}
 827
 828int cmd_rebase(int argc, const char **argv, const char *prefix)
 829{
 830        struct rebase_options options = {
 831                .type = REBASE_UNSPECIFIED,
 832                .flags = REBASE_NO_QUIET,
 833                .git_am_opts = ARGV_ARRAY_INIT,
 834                .allow_rerere_autoupdate  = -1,
 835                .allow_empty_message = 1,
 836                .git_format_patch_opt = STRBUF_INIT,
 837        };
 838        const char *branch_name;
 839        int ret, flags, total_argc, in_progress = 0;
 840        int ok_to_skip_pre_rebase = 0;
 841        struct strbuf msg = STRBUF_INIT;
 842        struct strbuf revisions = STRBUF_INIT;
 843        struct strbuf buf = STRBUF_INIT;
 844        struct object_id merge_base;
 845        enum {
 846                NO_ACTION,
 847                ACTION_CONTINUE,
 848                ACTION_SKIP,
 849                ACTION_ABORT,
 850                ACTION_QUIT,
 851                ACTION_EDIT_TODO,
 852                ACTION_SHOW_CURRENT_PATCH,
 853        } action = NO_ACTION;
 854        const char *gpg_sign = NULL;
 855        struct string_list exec = STRING_LIST_INIT_NODUP;
 856        const char *rebase_merges = NULL;
 857        int fork_point = -1;
 858        struct string_list strategy_options = STRING_LIST_INIT_NODUP;
 859        struct object_id squash_onto;
 860        char *squash_onto_name = NULL;
 861        struct opt_y opt_y = { .list = &exec, .options = &options };
 862        struct option builtin_rebase_options[] = {
 863                OPT_STRING(0, "onto", &options.onto_name,
 864                           N_("revision"),
 865                           N_("rebase onto given branch instead of upstream")),
 866                OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
 867                         N_("allow pre-rebase hook to run")),
 868                OPT_NEGBIT('q', "quiet", &options.flags,
 869                           N_("be quiet. implies --no-stat"),
 870                           REBASE_NO_QUIET| REBASE_VERBOSE | REBASE_DIFFSTAT),
 871                OPT_BIT('v', "verbose", &options.flags,
 872                        N_("display a diffstat of what changed upstream"),
 873                        REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
 874                {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
 875                        N_("do not show diffstat of what changed upstream"),
 876                        PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
 877                OPT_BOOL(0, "signoff", &options.signoff,
 878                         N_("add a Signed-off-by: line to each commit")),
 879                OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &options.git_am_opts,
 880                                  NULL, N_("passed to 'git am'"),
 881                                  PARSE_OPT_NOARG),
 882                OPT_PASSTHRU_ARGV(0, "committer-date-is-author-date",
 883                                  &options.git_am_opts, NULL,
 884                                  N_("passed to 'git am'"), PARSE_OPT_NOARG),
 885                OPT_PASSTHRU_ARGV(0, "ignore-date", &options.git_am_opts, NULL,
 886                                  N_("passed to 'git am'"), PARSE_OPT_NOARG),
 887                OPT_PASSTHRU_ARGV('C', NULL, &options.git_am_opts, N_("n"),
 888                                  N_("passed to 'git apply'"), 0),
 889                OPT_PASSTHRU_ARGV(0, "whitespace", &options.git_am_opts,
 890                                  N_("action"), N_("passed to 'git apply'"), 0),
 891                OPT_BIT('f', "force-rebase", &options.flags,
 892                        N_("cherry-pick all commits, even if unchanged"),
 893                        REBASE_FORCE),
 894                OPT_BIT(0, "no-ff", &options.flags,
 895                        N_("cherry-pick all commits, even if unchanged"),
 896                        REBASE_FORCE),
 897                OPT_CMDMODE(0, "continue", &action, N_("continue"),
 898                            ACTION_CONTINUE),
 899                OPT_CMDMODE(0, "skip", &action,
 900                            N_("skip current patch and continue"), ACTION_SKIP),
 901                OPT_CMDMODE(0, "abort", &action,
 902                            N_("abort and check out the original branch"),
 903                            ACTION_ABORT),
 904                OPT_CMDMODE(0, "quit", &action,
 905                            N_("abort but keep HEAD where it is"), ACTION_QUIT),
 906                OPT_CMDMODE(0, "edit-todo", &action, N_("edit the todo list "
 907                            "during an interactive rebase"), ACTION_EDIT_TODO),
 908                OPT_CMDMODE(0, "show-current-patch", &action,
 909                            N_("show the patch file being applied or merged"),
 910                            ACTION_SHOW_CURRENT_PATCH),
 911                { OPTION_CALLBACK, 'm', "merge", &options, NULL,
 912                        N_("use merging strategies to rebase"),
 913                        PARSE_OPT_NOARG | PARSE_OPT_NONEG,
 914                        parse_opt_merge },
 915                { OPTION_CALLBACK, 'i', "interactive", &options, NULL,
 916                        N_("let the user edit the list of commits to rebase"),
 917                        PARSE_OPT_NOARG | PARSE_OPT_NONEG,
 918                        parse_opt_interactive },
 919                OPT_SET_INT('p', "preserve-merges", &options.type,
 920                            N_("try to recreate merges instead of ignoring "
 921                               "them"), REBASE_PRESERVE_MERGES),
 922                OPT_BOOL(0, "rerere-autoupdate",
 923                         &options.allow_rerere_autoupdate,
 924                         N_("allow rerere to update index with resolved "
 925                            "conflict")),
 926                OPT_BOOL('k', "keep-empty", &options.keep_empty,
 927                         N_("preserve empty commits during rebase")),
 928                OPT_BOOL(0, "autosquash", &options.autosquash,
 929                         N_("move commits that begin with "
 930                            "squash!/fixup! under -i")),
 931                { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
 932                        N_("GPG-sign commits"),
 933                        PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
 934                OPT_BOOL(0, "autostash", &options.autostash,
 935                         N_("automatically stash/stash pop before and after")),
 936                OPT_STRING_LIST('x', "exec", &exec, N_("exec"),
 937                                N_("add exec lines after each commit of the "
 938                                   "editable list")),
 939                { OPTION_CALLBACK, 'y', NULL, &opt_y, N_("<cmd>"),
 940                        N_("same as --reschedule-failed-exec -x <cmd>"),
 941                        PARSE_OPT_NONEG, parse_opt_y },
 942                OPT_BOOL(0, "allow-empty-message",
 943                         &options.allow_empty_message,
 944                         N_("allow rebasing commits with empty messages")),
 945                {OPTION_STRING, 'r', "rebase-merges", &rebase_merges,
 946                        N_("mode"),
 947                        N_("try to rebase merges instead of skipping them"),
 948                        PARSE_OPT_OPTARG, NULL, (intptr_t)""},
 949                OPT_BOOL(0, "fork-point", &fork_point,
 950                         N_("use 'merge-base --fork-point' to refine upstream")),
 951                OPT_STRING('s', "strategy", &options.strategy,
 952                           N_("strategy"), N_("use the given merge strategy")),
 953                OPT_STRING_LIST('X', "strategy-option", &strategy_options,
 954                                N_("option"),
 955                                N_("pass the argument through to the merge "
 956                                   "strategy")),
 957                OPT_BOOL(0, "root", &options.root,
 958                         N_("rebase all reachable commits up to the root(s)")),
 959                OPT_BOOL(0, "reschedule-failed-exec",
 960                         &options.reschedule_failed_exec,
 961                         N_("automatically re-schedule any `exec` that fails")),
 962                OPT_END(),
 963        };
 964        int i;
 965
 966        /*
 967         * NEEDSWORK: Once the builtin rebase has been tested enough
 968         * and git-legacy-rebase.sh is retired to contrib/, this preamble
 969         * can be removed.
 970         */
 971
 972        if (!use_builtin_rebase()) {
 973                const char *path = mkpath("%s/git-legacy-rebase",
 974                                          git_exec_path());
 975
 976                if (sane_execvp(path, (char **)argv) < 0)
 977                        die_errno(_("could not exec %s"), path);
 978                else
 979                        BUG("sane_execvp() returned???");
 980        }
 981
 982        if (argc == 2 && !strcmp(argv[1], "-h"))
 983                usage_with_options(builtin_rebase_usage,
 984                                   builtin_rebase_options);
 985
 986        prefix = setup_git_directory();
 987        trace_repo_setup(prefix);
 988        setup_work_tree();
 989
 990        git_config(rebase_config, &options);
 991
 992        strbuf_reset(&buf);
 993        strbuf_addf(&buf, "%s/applying", apply_dir());
 994        if(file_exists(buf.buf))
 995                die(_("It looks like 'git am' is in progress. Cannot rebase."));
 996
 997        if (is_directory(apply_dir())) {
 998                options.type = REBASE_AM;
 999                options.state_dir = apply_dir();
1000        } else if (is_directory(merge_dir())) {
1001                strbuf_reset(&buf);
1002                strbuf_addf(&buf, "%s/rewritten", merge_dir());
1003                if (is_directory(buf.buf)) {
1004                        options.type = REBASE_PRESERVE_MERGES;
1005                        options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1006                } else {
1007                        strbuf_reset(&buf);
1008                        strbuf_addf(&buf, "%s/interactive", merge_dir());
1009                        if(file_exists(buf.buf)) {
1010                                options.type = REBASE_INTERACTIVE;
1011                                options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1012                        } else
1013                                options.type = REBASE_MERGE;
1014                }
1015                options.state_dir = merge_dir();
1016        }
1017
1018        if (options.type != REBASE_UNSPECIFIED)
1019                in_progress = 1;
1020
1021        total_argc = argc;
1022        argc = parse_options(argc, argv, prefix,
1023                             builtin_rebase_options,
1024                             builtin_rebase_usage, 0);
1025
1026        if (action != NO_ACTION && total_argc != 2) {
1027                usage_with_options(builtin_rebase_usage,
1028                                   builtin_rebase_options);
1029        }
1030
1031        if (argc > 2)
1032                usage_with_options(builtin_rebase_usage,
1033                                   builtin_rebase_options);
1034
1035        if (action != NO_ACTION && !in_progress)
1036                die(_("No rebase in progress?"));
1037        setenv(GIT_REFLOG_ACTION_ENVIRONMENT, "rebase", 0);
1038
1039        if (action == ACTION_EDIT_TODO && !is_interactive(&options))
1040                die(_("The --edit-todo action can only be used during "
1041                      "interactive rebase."));
1042
1043        switch (action) {
1044        case ACTION_CONTINUE: {
1045                struct object_id head;
1046                struct lock_file lock_file = LOCK_INIT;
1047                int fd;
1048
1049                options.action = "continue";
1050                set_reflog_action(&options);
1051
1052                /* Sanity check */
1053                if (get_oid("HEAD", &head))
1054                        die(_("Cannot read HEAD"));
1055
1056                fd = hold_locked_index(&lock_file, 0);
1057                if (read_index(the_repository->index) < 0)
1058                        die(_("could not read index"));
1059                refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
1060                              NULL);
1061                if (0 <= fd)
1062                        update_index_if_able(the_repository->index,
1063                                             &lock_file);
1064                rollback_lock_file(&lock_file);
1065
1066                if (has_unstaged_changes(the_repository, 1)) {
1067                        puts(_("You must edit all merge conflicts and then\n"
1068                               "mark them as resolved using git add"));
1069                        exit(1);
1070                }
1071                if (read_basic_state(&options))
1072                        exit(1);
1073                goto run_rebase;
1074        }
1075        case ACTION_SKIP: {
1076                struct string_list merge_rr = STRING_LIST_INIT_DUP;
1077
1078                options.action = "skip";
1079                set_reflog_action(&options);
1080
1081                rerere_clear(the_repository, &merge_rr);
1082                string_list_clear(&merge_rr, 1);
1083
1084                if (reset_head(NULL, "reset", NULL, RESET_HEAD_HARD,
1085                               NULL, NULL) < 0)
1086                        die(_("could not discard worktree changes"));
1087                remove_branch_state(the_repository);
1088                if (read_basic_state(&options))
1089                        exit(1);
1090                goto run_rebase;
1091        }
1092        case ACTION_ABORT: {
1093                struct string_list merge_rr = STRING_LIST_INIT_DUP;
1094                options.action = "abort";
1095                set_reflog_action(&options);
1096
1097                rerere_clear(the_repository, &merge_rr);
1098                string_list_clear(&merge_rr, 1);
1099
1100                if (read_basic_state(&options))
1101                        exit(1);
1102                if (reset_head(&options.orig_head, "reset",
1103                               options.head_name, RESET_HEAD_HARD,
1104                               NULL, NULL) < 0)
1105                        die(_("could not move back to %s"),
1106                            oid_to_hex(&options.orig_head));
1107                remove_branch_state(the_repository);
1108                ret = finish_rebase(&options);
1109                goto cleanup;
1110        }
1111        case ACTION_QUIT: {
1112                strbuf_reset(&buf);
1113                strbuf_addstr(&buf, options.state_dir);
1114                ret = !!remove_dir_recursively(&buf, 0);
1115                if (ret)
1116                        die(_("could not remove '%s'"), options.state_dir);
1117                goto cleanup;
1118        }
1119        case ACTION_EDIT_TODO:
1120                options.action = "edit-todo";
1121                options.dont_finish_rebase = 1;
1122                goto run_rebase;
1123        case ACTION_SHOW_CURRENT_PATCH:
1124                options.action = "show-current-patch";
1125                options.dont_finish_rebase = 1;
1126                goto run_rebase;
1127        case NO_ACTION:
1128                break;
1129        default:
1130                BUG("action: %d", action);
1131        }
1132
1133        /* Make sure no rebase is in progress */
1134        if (in_progress) {
1135                const char *last_slash = strrchr(options.state_dir, '/');
1136                const char *state_dir_base =
1137                        last_slash ? last_slash + 1 : options.state_dir;
1138                const char *cmd_live_rebase =
1139                        "git rebase (--continue | --abort | --skip)";
1140                strbuf_reset(&buf);
1141                strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
1142                die(_("It seems that there is already a %s directory, and\n"
1143                      "I wonder if you are in the middle of another rebase.  "
1144                      "If that is the\n"
1145                      "case, please try\n\t%s\n"
1146                      "If that is not the case, please\n\t%s\n"
1147                      "and run me again.  I am stopping in case you still "
1148                      "have something\n"
1149                      "valuable there.\n"),
1150                    state_dir_base, cmd_live_rebase, buf.buf);
1151        }
1152
1153        for (i = 0; i < options.git_am_opts.argc; i++) {
1154                const char *option = options.git_am_opts.argv[i], *p;
1155                if (!strcmp(option, "--committer-date-is-author-date") ||
1156                    !strcmp(option, "--ignore-date") ||
1157                    !strcmp(option, "--whitespace=fix") ||
1158                    !strcmp(option, "--whitespace=strip"))
1159                        options.flags |= REBASE_FORCE;
1160                else if (skip_prefix(option, "-C", &p)) {
1161                        while (*p)
1162                                if (!isdigit(*(p++)))
1163                                        die(_("switch `C' expects a "
1164                                              "numerical value"));
1165                } else if (skip_prefix(option, "--whitespace=", &p)) {
1166                        if (*p && strcmp(p, "warn") && strcmp(p, "nowarn") &&
1167                            strcmp(p, "error") && strcmp(p, "error-all"))
1168                                die("Invalid whitespace option: '%s'", p);
1169                }
1170        }
1171
1172        if (!(options.flags & REBASE_NO_QUIET))
1173                argv_array_push(&options.git_am_opts, "-q");
1174
1175        if (options.keep_empty)
1176                imply_interactive(&options, "--keep-empty");
1177
1178        if (gpg_sign) {
1179                free(options.gpg_sign_opt);
1180                options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
1181        }
1182
1183        if (exec.nr) {
1184                int i;
1185
1186                imply_interactive(&options, "--exec");
1187
1188                strbuf_reset(&buf);
1189                for (i = 0; i < exec.nr; i++)
1190                        strbuf_addf(&buf, "exec %s\n", exec.items[i].string);
1191                options.cmd = xstrdup(buf.buf);
1192        }
1193
1194        if (rebase_merges) {
1195                if (!*rebase_merges)
1196                        ; /* default mode; do nothing */
1197                else if (!strcmp("rebase-cousins", rebase_merges))
1198                        options.rebase_cousins = 1;
1199                else if (strcmp("no-rebase-cousins", rebase_merges))
1200                        die(_("Unknown mode: %s"), rebase_merges);
1201                options.rebase_merges = 1;
1202                imply_interactive(&options, "--rebase-merges");
1203        }
1204
1205        if (strategy_options.nr) {
1206                int i;
1207
1208                if (!options.strategy)
1209                        options.strategy = "recursive";
1210
1211                strbuf_reset(&buf);
1212                for (i = 0; i < strategy_options.nr; i++)
1213                        strbuf_addf(&buf, " --%s",
1214                                    strategy_options.items[i].string);
1215                options.strategy_opts = xstrdup(buf.buf);
1216        }
1217
1218        if (options.strategy) {
1219                options.strategy = xstrdup(options.strategy);
1220                switch (options.type) {
1221                case REBASE_AM:
1222                        die(_("--strategy requires --merge or --interactive"));
1223                case REBASE_MERGE:
1224                case REBASE_INTERACTIVE:
1225                case REBASE_PRESERVE_MERGES:
1226                        /* compatible */
1227                        break;
1228                case REBASE_UNSPECIFIED:
1229                        options.type = REBASE_MERGE;
1230                        break;
1231                default:
1232                        BUG("unhandled rebase type (%d)", options.type);
1233                }
1234        }
1235
1236        if (options.root && !options.onto_name)
1237                imply_interactive(&options, "--root without --onto");
1238
1239        if (isatty(2) && options.flags & REBASE_NO_QUIET)
1240                strbuf_addstr(&options.git_format_patch_opt, " --progress");
1241
1242        switch (options.type) {
1243        case REBASE_MERGE:
1244        case REBASE_INTERACTIVE:
1245        case REBASE_PRESERVE_MERGES:
1246                options.state_dir = merge_dir();
1247                break;
1248        case REBASE_AM:
1249                options.state_dir = apply_dir();
1250                break;
1251        default:
1252                /* the default rebase backend is `--am` */
1253                options.type = REBASE_AM;
1254                options.state_dir = apply_dir();
1255                break;
1256        }
1257
1258        if (options.reschedule_failed_exec && !is_interactive(&options))
1259                die(_("--reschedule-failed-exec requires an interactive rebase"));
1260
1261        if (options.git_am_opts.argc) {
1262                /* all am options except -q are compatible only with --am */
1263                for (i = options.git_am_opts.argc - 1; i >= 0; i--)
1264                        if (strcmp(options.git_am_opts.argv[i], "-q"))
1265                                break;
1266
1267                if (is_interactive(&options) && i >= 0)
1268                        die(_("error: cannot combine interactive options "
1269                              "(--interactive, --exec, --rebase-merges, "
1270                              "--preserve-merges, --keep-empty, --root + "
1271                              "--onto) with am options (%s)"), buf.buf);
1272                if (options.type == REBASE_MERGE && i >= 0)
1273                        die(_("error: cannot combine merge options (--merge, "
1274                              "--strategy, --strategy-option) with am options "
1275                              "(%s)"), buf.buf);
1276        }
1277
1278        if (options.signoff) {
1279                if (options.type == REBASE_PRESERVE_MERGES)
1280                        die("cannot combine '--signoff' with "
1281                            "'--preserve-merges'");
1282                argv_array_push(&options.git_am_opts, "--signoff");
1283                options.flags |= REBASE_FORCE;
1284        }
1285
1286        if (options.type == REBASE_PRESERVE_MERGES) {
1287                /*
1288                 * Note: incompatibility with --signoff handled in signoff block above
1289                 * Note: incompatibility with --interactive is just a strong warning;
1290                 *       git-rebase.txt caveats with "unless you know what you are doing"
1291                 */
1292                if (options.rebase_merges)
1293                        die(_("error: cannot combine '--preserve-merges' with "
1294                              "'--rebase-merges'"));
1295
1296                if (options.reschedule_failed_exec)
1297                        die(_("error: cannot combine '--preserve-merges' with "
1298                              "'--reschedule-failed-exec'"));
1299        }
1300
1301        if (options.rebase_merges) {
1302                if (strategy_options.nr)
1303                        die(_("error: cannot combine '--rebase-merges' with "
1304                              "'--strategy-option'"));
1305                if (options.strategy)
1306                        die(_("error: cannot combine '--rebase-merges' with "
1307                              "'--strategy'"));
1308        }
1309
1310        if (!options.root) {
1311                if (argc < 1) {
1312                        struct branch *branch;
1313
1314                        branch = branch_get(NULL);
1315                        options.upstream_name = branch_get_upstream(branch,
1316                                                                    NULL);
1317                        if (!options.upstream_name)
1318                                error_on_missing_default_upstream();
1319                        if (fork_point < 0)
1320                                fork_point = 1;
1321                } else {
1322                        options.upstream_name = argv[0];
1323                        argc--;
1324                        argv++;
1325                        if (!strcmp(options.upstream_name, "-"))
1326                                options.upstream_name = "@{-1}";
1327                }
1328                options.upstream = peel_committish(options.upstream_name);
1329                if (!options.upstream)
1330                        die(_("invalid upstream '%s'"), options.upstream_name);
1331                options.upstream_arg = options.upstream_name;
1332        } else {
1333                if (!options.onto_name) {
1334                        if (commit_tree("", 0, the_hash_algo->empty_tree, NULL,
1335                                        &squash_onto, NULL, NULL) < 0)
1336                                die(_("Could not create new root commit"));
1337                        options.squash_onto = &squash_onto;
1338                        options.onto_name = squash_onto_name =
1339                                xstrdup(oid_to_hex(&squash_onto));
1340                }
1341                options.upstream_name = NULL;
1342                options.upstream = NULL;
1343                if (argc > 1)
1344                        usage_with_options(builtin_rebase_usage,
1345                                           builtin_rebase_options);
1346                options.upstream_arg = "--root";
1347        }
1348
1349        /* Make sure the branch to rebase onto is valid. */
1350        if (!options.onto_name)
1351                options.onto_name = options.upstream_name;
1352        if (strstr(options.onto_name, "...")) {
1353                if (get_oid_mb(options.onto_name, &merge_base) < 0)
1354                        die(_("'%s': need exactly one merge base"),
1355                            options.onto_name);
1356                options.onto = lookup_commit_or_die(&merge_base,
1357                                                    options.onto_name);
1358        } else {
1359                options.onto = peel_committish(options.onto_name);
1360                if (!options.onto)
1361                        die(_("Does not point to a valid commit '%s'"),
1362                                options.onto_name);
1363        }
1364
1365        /*
1366         * If the branch to rebase is given, that is the branch we will rebase
1367         * branch_name -- branch/commit being rebased, or
1368         *                HEAD (already detached)
1369         * orig_head -- commit object name of tip of the branch before rebasing
1370         * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
1371         */
1372        if (argc == 1) {
1373                /* Is it "rebase other branchname" or "rebase other commit"? */
1374                branch_name = argv[0];
1375                options.switch_to = argv[0];
1376
1377                /* Is it a local branch? */
1378                strbuf_reset(&buf);
1379                strbuf_addf(&buf, "refs/heads/%s", branch_name);
1380                if (!read_ref(buf.buf, &options.orig_head))
1381                        options.head_name = xstrdup(buf.buf);
1382                /* If not is it a valid ref (branch or commit)? */
1383                else if (!get_oid(branch_name, &options.orig_head))
1384                        options.head_name = NULL;
1385                else
1386                        die(_("fatal: no such branch/commit '%s'"),
1387                            branch_name);
1388        } else if (argc == 0) {
1389                /* Do not need to switch branches, we are already on it. */
1390                options.head_name =
1391                        xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
1392                                         &flags));
1393                if (!options.head_name)
1394                        die(_("No such ref: %s"), "HEAD");
1395                if (flags & REF_ISSYMREF) {
1396                        if (!skip_prefix(options.head_name,
1397                                         "refs/heads/", &branch_name))
1398                                branch_name = options.head_name;
1399
1400                } else {
1401                        free(options.head_name);
1402                        options.head_name = NULL;
1403                        branch_name = "HEAD";
1404                }
1405                if (get_oid("HEAD", &options.orig_head))
1406                        die(_("Could not resolve HEAD to a revision"));
1407        } else
1408                BUG("unexpected number of arguments left to parse");
1409
1410        if (fork_point > 0) {
1411                struct commit *head =
1412                        lookup_commit_reference(the_repository,
1413                                                &options.orig_head);
1414                options.restrict_revision =
1415                        get_fork_point(options.upstream_name, head);
1416        }
1417
1418        if (read_index(the_repository->index) < 0)
1419                die(_("could not read index"));
1420
1421        if (options.autostash) {
1422                struct lock_file lock_file = LOCK_INIT;
1423                int fd;
1424
1425                fd = hold_locked_index(&lock_file, 0);
1426                refresh_cache(REFRESH_QUIET);
1427                if (0 <= fd)
1428                        update_index_if_able(&the_index, &lock_file);
1429                rollback_lock_file(&lock_file);
1430
1431                if (has_unstaged_changes(the_repository, 1) ||
1432                    has_uncommitted_changes(the_repository, 1)) {
1433                        const char *autostash =
1434                                state_dir_path("autostash", &options);
1435                        struct child_process stash = CHILD_PROCESS_INIT;
1436                        struct object_id oid;
1437                        struct commit *head =
1438                                lookup_commit_reference(the_repository,
1439                                                        &options.orig_head);
1440
1441                        argv_array_pushl(&stash.args,
1442                                         "stash", "create", "autostash", NULL);
1443                        stash.git_cmd = 1;
1444                        stash.no_stdin = 1;
1445                        strbuf_reset(&buf);
1446                        if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
1447                                die(_("Cannot autostash"));
1448                        strbuf_trim_trailing_newline(&buf);
1449                        if (get_oid(buf.buf, &oid))
1450                                die(_("Unexpected stash response: '%s'"),
1451                                    buf.buf);
1452                        strbuf_reset(&buf);
1453                        strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
1454
1455                        if (safe_create_leading_directories_const(autostash))
1456                                die(_("Could not create directory for '%s'"),
1457                                    options.state_dir);
1458                        write_file(autostash, "%s", oid_to_hex(&oid));
1459                        printf(_("Created autostash: %s\n"), buf.buf);
1460                        if (reset_head(&head->object.oid, "reset --hard",
1461                                       NULL, RESET_HEAD_HARD, NULL, NULL) < 0)
1462                                die(_("could not reset --hard"));
1463                        printf(_("HEAD is now at %s"),
1464                               find_unique_abbrev(&head->object.oid,
1465                                                  DEFAULT_ABBREV));
1466                        strbuf_reset(&buf);
1467                        pp_commit_easy(CMIT_FMT_ONELINE, head, &buf);
1468                        if (buf.len > 0)
1469                                printf(" %s", buf.buf);
1470                        putchar('\n');
1471
1472                        if (discard_index(the_repository->index) < 0 ||
1473                                read_index(the_repository->index) < 0)
1474                                die(_("could not read index"));
1475                }
1476        }
1477
1478        if (require_clean_work_tree(the_repository, "rebase",
1479                                    _("Please commit or stash them."), 1, 1)) {
1480                ret = 1;
1481                goto cleanup;
1482        }
1483
1484        /*
1485         * Now we are rebasing commits upstream..orig_head (or with --root,
1486         * everything leading up to orig_head) on top of onto.
1487         */
1488
1489        /*
1490         * Check if we are already based on onto with linear history,
1491         * but this should be done only when upstream and onto are the same
1492         * and if this is not an interactive rebase.
1493         */
1494        if (can_fast_forward(options.onto, &options.orig_head, &merge_base) &&
1495            !is_interactive(&options) && !options.restrict_revision &&
1496            options.upstream &&
1497            !oidcmp(&options.upstream->object.oid, &options.onto->object.oid)) {
1498                int flag;
1499
1500                if (!(options.flags & REBASE_FORCE)) {
1501                        /* Lazily switch to the target branch if needed... */
1502                        if (options.switch_to) {
1503                                struct object_id oid;
1504
1505                                if (get_oid(options.switch_to, &oid) < 0) {
1506                                        ret = !!error(_("could not parse '%s'"),
1507                                                      options.switch_to);
1508                                        goto cleanup;
1509                                }
1510
1511                                strbuf_reset(&buf);
1512                                strbuf_addf(&buf, "%s: checkout %s",
1513                                            getenv(GIT_REFLOG_ACTION_ENVIRONMENT),
1514                                            options.switch_to);
1515                                if (reset_head(&oid, "checkout",
1516                                               options.head_name,
1517                                               RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
1518                                               NULL, buf.buf) < 0) {
1519                                        ret = !!error(_("could not switch to "
1520                                                        "%s"),
1521                                                      options.switch_to);
1522                                        goto cleanup;
1523                                }
1524                        }
1525
1526                        if (!(options.flags & REBASE_NO_QUIET))
1527                                ; /* be quiet */
1528                        else if (!strcmp(branch_name, "HEAD") &&
1529                                 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1530                                puts(_("HEAD is up to date."));
1531                        else
1532                                printf(_("Current branch %s is up to date.\n"),
1533                                       branch_name);
1534                        ret = !!finish_rebase(&options);
1535                        goto cleanup;
1536                } else if (!(options.flags & REBASE_NO_QUIET))
1537                        ; /* be quiet */
1538                else if (!strcmp(branch_name, "HEAD") &&
1539                         resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1540                        puts(_("HEAD is up to date, rebase forced."));
1541                else
1542                        printf(_("Current branch %s is up to date, rebase "
1543                                 "forced.\n"), branch_name);
1544        }
1545
1546        /* If a hook exists, give it a chance to interrupt*/
1547        if (!ok_to_skip_pre_rebase &&
1548            run_hook_le(NULL, "pre-rebase", options.upstream_arg,
1549                        argc ? argv[0] : NULL, NULL))
1550                die(_("The pre-rebase hook refused to rebase."));
1551
1552        if (options.flags & REBASE_DIFFSTAT) {
1553                struct diff_options opts;
1554
1555                if (options.flags & REBASE_VERBOSE) {
1556                        if (is_null_oid(&merge_base))
1557                                printf(_("Changes to %s:\n"),
1558                                       oid_to_hex(&options.onto->object.oid));
1559                        else
1560                                printf(_("Changes from %s to %s:\n"),
1561                                       oid_to_hex(&merge_base),
1562                                       oid_to_hex(&options.onto->object.oid));
1563                }
1564
1565                /* We want color (if set), but no pager */
1566                diff_setup(&opts);
1567                opts.stat_width = -1; /* use full terminal width */
1568                opts.stat_graph_width = -1; /* respect statGraphWidth config */
1569                opts.output_format |=
1570                        DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1571                opts.detect_rename = DIFF_DETECT_RENAME;
1572                diff_setup_done(&opts);
1573                diff_tree_oid(is_null_oid(&merge_base) ?
1574                              the_hash_algo->empty_tree : &merge_base,
1575                              &options.onto->object.oid, "", &opts);
1576                diffcore_std(&opts);
1577                diff_flush(&opts);
1578        }
1579
1580        if (is_interactive(&options))
1581                goto run_rebase;
1582
1583        /* Detach HEAD and reset the tree */
1584        if (options.flags & REBASE_NO_QUIET)
1585                printf(_("First, rewinding head to replay your work on top of "
1586                         "it...\n"));
1587
1588        strbuf_addf(&msg, "%s: checkout %s",
1589                    getenv(GIT_REFLOG_ACTION_ENVIRONMENT), options.onto_name);
1590        if (reset_head(&options.onto->object.oid, "checkout", NULL,
1591                       RESET_HEAD_DETACH | RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
1592                       NULL, msg.buf))
1593                die(_("Could not detach HEAD"));
1594        strbuf_release(&msg);
1595
1596        /*
1597         * If the onto is a proper descendant of the tip of the branch, then
1598         * we just fast-forwarded.
1599         */
1600        strbuf_reset(&msg);
1601        if (!oidcmp(&merge_base, &options.orig_head)) {
1602                printf(_("Fast-forwarded %s to %s.\n"),
1603                        branch_name, options.onto_name);
1604                strbuf_addf(&msg, "rebase finished: %s onto %s",
1605                        options.head_name ? options.head_name : "detached HEAD",
1606                        oid_to_hex(&options.onto->object.oid));
1607                reset_head(NULL, "Fast-forwarded", options.head_name, 0,
1608                           "HEAD", msg.buf);
1609                strbuf_release(&msg);
1610                ret = !!finish_rebase(&options);
1611                goto cleanup;
1612        }
1613
1614        strbuf_addf(&revisions, "%s..%s",
1615                    options.root ? oid_to_hex(&options.onto->object.oid) :
1616                    (options.restrict_revision ?
1617                     oid_to_hex(&options.restrict_revision->object.oid) :
1618                     oid_to_hex(&options.upstream->object.oid)),
1619                    oid_to_hex(&options.orig_head));
1620
1621        options.revisions = revisions.buf;
1622
1623run_rebase:
1624        ret = !!run_specific_rebase(&options);
1625
1626cleanup:
1627        strbuf_release(&revisions);
1628        free(options.head_name);
1629        free(options.gpg_sign_opt);
1630        free(options.cmd);
1631        free(squash_onto_name);
1632        return ret;
1633}