730aefb7a9ea3cbc84c5457b6a8241e546c3df29
   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 "rerere.h"
  25
  26static char const * const builtin_rebase_usage[] = {
  27        N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
  28                "[<upstream>] [<branch>]"),
  29        N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
  30                "--root [<branch>]"),
  31        N_("git rebase --continue | --abort | --skip | --edit-todo"),
  32        NULL
  33};
  34
  35static GIT_PATH_FUNC(apply_dir, "rebase-apply")
  36static GIT_PATH_FUNC(merge_dir, "rebase-merge")
  37
  38enum rebase_type {
  39        REBASE_UNSPECIFIED = -1,
  40        REBASE_AM,
  41        REBASE_MERGE,
  42        REBASE_INTERACTIVE,
  43        REBASE_PRESERVE_MERGES
  44};
  45
  46static int use_builtin_rebase(void)
  47{
  48        struct child_process cp = CHILD_PROCESS_INIT;
  49        struct strbuf out = STRBUF_INIT;
  50        int ret;
  51
  52        argv_array_pushl(&cp.args,
  53                         "config", "--bool", "rebase.usebuiltin", NULL);
  54        cp.git_cmd = 1;
  55        if (capture_command(&cp, &out, 6)) {
  56                strbuf_release(&out);
  57                return 0;
  58        }
  59
  60        strbuf_trim(&out);
  61        ret = !strcmp("true", out.buf);
  62        strbuf_release(&out);
  63        return ret;
  64}
  65
  66struct rebase_options {
  67        enum rebase_type type;
  68        const char *state_dir;
  69        struct commit *upstream;
  70        const char *upstream_name;
  71        const char *upstream_arg;
  72        char *head_name;
  73        struct object_id orig_head;
  74        struct commit *onto;
  75        const char *onto_name;
  76        const char *revisions;
  77        const char *switch_to;
  78        int root;
  79        struct commit *restrict_revision;
  80        int dont_finish_rebase;
  81        enum {
  82                REBASE_NO_QUIET = 1<<0,
  83                REBASE_VERBOSE = 1<<1,
  84                REBASE_DIFFSTAT = 1<<2,
  85                REBASE_FORCE = 1<<3,
  86                REBASE_INTERACTIVE_EXPLICIT = 1<<4,
  87        } flags;
  88        struct strbuf git_am_opt;
  89        const char *action;
  90        int signoff;
  91        int allow_rerere_autoupdate;
  92        int keep_empty;
  93        int autosquash;
  94        char *gpg_sign_opt;
  95        int autostash;
  96        char *cmd;
  97        int allow_empty_message;
  98};
  99
 100static int is_interactive(struct rebase_options *opts)
 101{
 102        return opts->type == REBASE_INTERACTIVE ||
 103                opts->type == REBASE_PRESERVE_MERGES;
 104}
 105
 106static void imply_interactive(struct rebase_options *opts, const char *option)
 107{
 108        switch (opts->type) {
 109        case REBASE_AM:
 110                die(_("%s requires an interactive rebase"), option);
 111                break;
 112        case REBASE_INTERACTIVE:
 113        case REBASE_PRESERVE_MERGES:
 114                break;
 115        case REBASE_MERGE:
 116                /* we silently *upgrade* --merge to --interactive if needed */
 117        default:
 118                opts->type = REBASE_INTERACTIVE; /* implied */
 119                break;
 120        }
 121}
 122
 123/* Returns the filename prefixed by the state_dir */
 124static const char *state_dir_path(const char *filename, struct rebase_options *opts)
 125{
 126        static struct strbuf path = STRBUF_INIT;
 127        static size_t prefix_len;
 128
 129        if (!prefix_len) {
 130                strbuf_addf(&path, "%s/", opts->state_dir);
 131                prefix_len = path.len;
 132        }
 133
 134        strbuf_setlen(&path, prefix_len);
 135        strbuf_addstr(&path, filename);
 136        return path.buf;
 137}
 138
 139/* Read one file, then strip line endings */
 140static int read_one(const char *path, struct strbuf *buf)
 141{
 142        if (strbuf_read_file(buf, path, 0) < 0)
 143                return error_errno(_("could not read '%s'"), path);
 144        strbuf_trim_trailing_newline(buf);
 145        return 0;
 146}
 147
 148/* Initialize the rebase options from the state directory. */
 149static int read_basic_state(struct rebase_options *opts)
 150{
 151        struct strbuf head_name = STRBUF_INIT;
 152        struct strbuf buf = STRBUF_INIT;
 153        struct object_id oid;
 154
 155        if (read_one(state_dir_path("head-name", opts), &head_name) ||
 156            read_one(state_dir_path("onto", opts), &buf))
 157                return -1;
 158        opts->head_name = starts_with(head_name.buf, "refs/") ?
 159                xstrdup(head_name.buf) : NULL;
 160        strbuf_release(&head_name);
 161        if (get_oid(buf.buf, &oid))
 162                return error(_("could not get 'onto': '%s'"), buf.buf);
 163        opts->onto = lookup_commit_or_die(&oid, buf.buf);
 164
 165        /*
 166         * We always write to orig-head, but interactive rebase used to write to
 167         * head. Fall back to reading from head to cover for the case that the
 168         * user upgraded git with an ongoing interactive rebase.
 169         */
 170        strbuf_reset(&buf);
 171        if (file_exists(state_dir_path("orig-head", opts))) {
 172                if (read_one(state_dir_path("orig-head", opts), &buf))
 173                        return -1;
 174        } else if (read_one(state_dir_path("head", opts), &buf))
 175                return -1;
 176        if (get_oid(buf.buf, &opts->orig_head))
 177                return error(_("invalid orig-head: '%s'"), buf.buf);
 178
 179        strbuf_reset(&buf);
 180        if (read_one(state_dir_path("quiet", opts), &buf))
 181                return -1;
 182        if (buf.len)
 183                opts->flags &= ~REBASE_NO_QUIET;
 184        else
 185                opts->flags |= REBASE_NO_QUIET;
 186
 187        if (file_exists(state_dir_path("verbose", opts)))
 188                opts->flags |= REBASE_VERBOSE;
 189
 190        if (file_exists(state_dir_path("signoff", opts))) {
 191                opts->signoff = 1;
 192                opts->flags |= REBASE_FORCE;
 193        }
 194
 195        if (file_exists(state_dir_path("allow_rerere_autoupdate", opts))) {
 196                strbuf_reset(&buf);
 197                if (read_one(state_dir_path("allow_rerere_autoupdate", opts),
 198                            &buf))
 199                        return -1;
 200                if (!strcmp(buf.buf, "--rerere-autoupdate"))
 201                        opts->allow_rerere_autoupdate = 1;
 202                else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
 203                        opts->allow_rerere_autoupdate = 0;
 204                else
 205                        warning(_("ignoring invalid allow_rerere_autoupdate: "
 206                                  "'%s'"), buf.buf);
 207        } else
 208                opts->allow_rerere_autoupdate = -1;
 209
 210        if (file_exists(state_dir_path("gpg_sign_opt", opts))) {
 211                strbuf_reset(&buf);
 212                if (read_one(state_dir_path("gpg_sign_opt", opts),
 213                            &buf))
 214                        return -1;
 215                free(opts->gpg_sign_opt);
 216                opts->gpg_sign_opt = xstrdup(buf.buf);
 217        }
 218
 219        strbuf_release(&buf);
 220
 221        return 0;
 222}
 223
 224static int apply_autostash(struct rebase_options *opts)
 225{
 226        const char *path = state_dir_path("autostash", opts);
 227        struct strbuf autostash = STRBUF_INIT;
 228        struct child_process stash_apply = CHILD_PROCESS_INIT;
 229
 230        if (!file_exists(path))
 231                return 0;
 232
 233        if (read_one(state_dir_path("autostash", opts), &autostash))
 234                return error(_("Could not read '%s'"), path);
 235        argv_array_pushl(&stash_apply.args,
 236                         "stash", "apply", autostash.buf, NULL);
 237        stash_apply.git_cmd = 1;
 238        stash_apply.no_stderr = stash_apply.no_stdout =
 239                stash_apply.no_stdin = 1;
 240        if (!run_command(&stash_apply))
 241                printf(_("Applied autostash.\n"));
 242        else {
 243                struct argv_array args = ARGV_ARRAY_INIT;
 244                int res = 0;
 245
 246                argv_array_pushl(&args,
 247                                 "stash", "store", "-m", "autostash", "-q",
 248                                 autostash.buf, NULL);
 249                if (run_command_v_opt(args.argv, RUN_GIT_CMD))
 250                        res = error(_("Cannot store %s"), autostash.buf);
 251                argv_array_clear(&args);
 252                strbuf_release(&autostash);
 253                if (res)
 254                        return res;
 255
 256                fprintf(stderr,
 257                        _("Applying autostash resulted in conflicts.\n"
 258                          "Your changes are safe in the stash.\n"
 259                          "You can run \"git stash pop\" or \"git stash drop\" "
 260                          "at any time.\n"));
 261        }
 262
 263        strbuf_release(&autostash);
 264        return 0;
 265}
 266
 267static int finish_rebase(struct rebase_options *opts)
 268{
 269        struct strbuf dir = STRBUF_INIT;
 270        const char *argv_gc_auto[] = { "gc", "--auto", NULL };
 271
 272        delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
 273        apply_autostash(opts);
 274        close_all_packs(the_repository->objects);
 275        /*
 276         * We ignore errors in 'gc --auto', since the
 277         * user should see them.
 278         */
 279        run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
 280        strbuf_addstr(&dir, opts->state_dir);
 281        remove_dir_recursively(&dir, 0);
 282        strbuf_release(&dir);
 283
 284        return 0;
 285}
 286
 287static struct commit *peel_committish(const char *name)
 288{
 289        struct object *obj;
 290        struct object_id oid;
 291
 292        if (get_oid(name, &oid))
 293                return NULL;
 294        obj = parse_object(the_repository, &oid);
 295        return (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
 296}
 297
 298static void add_var(struct strbuf *buf, const char *name, const char *value)
 299{
 300        if (!value)
 301                strbuf_addf(buf, "unset %s; ", name);
 302        else {
 303                strbuf_addf(buf, "%s=", name);
 304                sq_quote_buf(buf, value);
 305                strbuf_addstr(buf, "; ");
 306        }
 307}
 308
 309static int run_specific_rebase(struct rebase_options *opts)
 310{
 311        const char *argv[] = { NULL, NULL };
 312        struct strbuf script_snippet = STRBUF_INIT;
 313        int status;
 314        const char *backend, *backend_func;
 315
 316        add_var(&script_snippet, "GIT_DIR", absolute_path(get_git_dir()));
 317        add_var(&script_snippet, "state_dir", opts->state_dir);
 318
 319        add_var(&script_snippet, "upstream_name", opts->upstream_name);
 320        add_var(&script_snippet, "upstream", opts->upstream ?
 321                oid_to_hex(&opts->upstream->object.oid) : NULL);
 322        add_var(&script_snippet, "head_name",
 323                opts->head_name ? opts->head_name : "detached HEAD");
 324        add_var(&script_snippet, "orig_head", oid_to_hex(&opts->orig_head));
 325        add_var(&script_snippet, "onto", opts->onto ?
 326                oid_to_hex(&opts->onto->object.oid) : NULL);
 327        add_var(&script_snippet, "onto_name", opts->onto_name);
 328        add_var(&script_snippet, "revisions", opts->revisions);
 329        add_var(&script_snippet, "restrict_revision", opts->restrict_revision ?
 330                oid_to_hex(&opts->restrict_revision->object.oid) : NULL);
 331        add_var(&script_snippet, "GIT_QUIET",
 332                opts->flags & REBASE_NO_QUIET ? "" : "t");
 333        add_var(&script_snippet, "git_am_opt", opts->git_am_opt.buf);
 334        add_var(&script_snippet, "verbose",
 335                opts->flags & REBASE_VERBOSE ? "t" : "");
 336        add_var(&script_snippet, "diffstat",
 337                opts->flags & REBASE_DIFFSTAT ? "t" : "");
 338        add_var(&script_snippet, "force_rebase",
 339                opts->flags & REBASE_FORCE ? "t" : "");
 340        if (opts->switch_to)
 341                add_var(&script_snippet, "switch_to", opts->switch_to);
 342        add_var(&script_snippet, "action", opts->action ? opts->action : "");
 343        add_var(&script_snippet, "signoff", opts->signoff ? "--signoff" : "");
 344        add_var(&script_snippet, "allow_rerere_autoupdate",
 345                opts->allow_rerere_autoupdate < 0 ? "" :
 346                opts->allow_rerere_autoupdate ?
 347                "--rerere-autoupdate" : "--no-rerere-autoupdate");
 348        add_var(&script_snippet, "keep_empty", opts->keep_empty ? "yes" : "");
 349        add_var(&script_snippet, "autosquash", opts->autosquash ? "t" : "");
 350        add_var(&script_snippet, "gpg_sign_opt", opts->gpg_sign_opt);
 351        add_var(&script_snippet, "cmd", opts->cmd);
 352        add_var(&script_snippet, "allow_empty_message",
 353                opts->allow_empty_message ?  "--allow-empty-message" : "");
 354
 355        switch (opts->type) {
 356        case REBASE_AM:
 357                backend = "git-rebase--am";
 358                backend_func = "git_rebase__am";
 359                break;
 360        case REBASE_INTERACTIVE:
 361                backend = "git-rebase--interactive";
 362                backend_func = "git_rebase__interactive";
 363                break;
 364        case REBASE_MERGE:
 365                backend = "git-rebase--merge";
 366                backend_func = "git_rebase__merge";
 367                break;
 368        case REBASE_PRESERVE_MERGES:
 369                backend = "git-rebase--preserve-merges";
 370                backend_func = "git_rebase__preserve_merges";
 371                break;
 372        default:
 373                BUG("Unhandled rebase type %d", opts->type);
 374                break;
 375        }
 376
 377        strbuf_addf(&script_snippet,
 378                    ". git-sh-setup && . git-rebase--common &&"
 379                    " . %s && %s", backend, backend_func);
 380        argv[0] = script_snippet.buf;
 381
 382        status = run_command_v_opt(argv, RUN_USING_SHELL);
 383        if (opts->dont_finish_rebase)
 384                ; /* do nothing */
 385        else if (status == 0) {
 386                if (!file_exists(state_dir_path("stopped-sha", opts)))
 387                        finish_rebase(opts);
 388        } else if (status == 2) {
 389                struct strbuf dir = STRBUF_INIT;
 390
 391                apply_autostash(opts);
 392                strbuf_addstr(&dir, opts->state_dir);
 393                remove_dir_recursively(&dir, 0);
 394                strbuf_release(&dir);
 395                die("Nothing to do");
 396        }
 397
 398        strbuf_release(&script_snippet);
 399
 400        return status ? -1 : 0;
 401}
 402
 403#define GIT_REFLOG_ACTION_ENVIRONMENT "GIT_REFLOG_ACTION"
 404
 405static int reset_head(struct object_id *oid, const char *action,
 406                      const char *switch_to_branch, int detach_head)
 407{
 408        struct object_id head_oid;
 409        struct tree_desc desc;
 410        struct lock_file lock = LOCK_INIT;
 411        struct unpack_trees_options unpack_tree_opts;
 412        struct tree *tree;
 413        const char *reflog_action;
 414        struct strbuf msg = STRBUF_INIT;
 415        size_t prefix_len;
 416        struct object_id *orig = NULL, oid_orig,
 417                *old_orig = NULL, oid_old_orig;
 418        int ret = 0;
 419
 420        if (switch_to_branch && !starts_with(switch_to_branch, "refs/"))
 421                BUG("Not a fully qualified branch: '%s'", switch_to_branch);
 422
 423        if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
 424                return -1;
 425
 426        if (!oid) {
 427                if (get_oid("HEAD", &head_oid)) {
 428                        rollback_lock_file(&lock);
 429                        return error(_("could not determine HEAD revision"));
 430                }
 431                oid = &head_oid;
 432        }
 433
 434        memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
 435        setup_unpack_trees_porcelain(&unpack_tree_opts, action);
 436        unpack_tree_opts.head_idx = 1;
 437        unpack_tree_opts.src_index = the_repository->index;
 438        unpack_tree_opts.dst_index = the_repository->index;
 439        unpack_tree_opts.fn = oneway_merge;
 440        unpack_tree_opts.update = 1;
 441        unpack_tree_opts.merge = 1;
 442        if (!detach_head)
 443                unpack_tree_opts.reset = 1;
 444
 445        if (read_index_unmerged(the_repository->index) < 0) {
 446                rollback_lock_file(&lock);
 447                return error(_("could not read index"));
 448        }
 449
 450        if (!fill_tree_descriptor(&desc, oid)) {
 451                error(_("failed to find tree of %s"), oid_to_hex(oid));
 452                rollback_lock_file(&lock);
 453                free((void *)desc.buffer);
 454                return -1;
 455        }
 456
 457        if (unpack_trees(1, &desc, &unpack_tree_opts)) {
 458                rollback_lock_file(&lock);
 459                free((void *)desc.buffer);
 460                return -1;
 461        }
 462
 463        tree = parse_tree_indirect(oid);
 464        prime_cache_tree(the_repository->index, tree);
 465
 466        if (write_locked_index(the_repository->index, &lock, COMMIT_LOCK) < 0)
 467                ret = error(_("could not write index"));
 468        free((void *)desc.buffer);
 469
 470        if (ret)
 471                return ret;
 472
 473        reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
 474        strbuf_addf(&msg, "%s: ", reflog_action ? reflog_action : "rebase");
 475        prefix_len = msg.len;
 476
 477        if (!get_oid("ORIG_HEAD", &oid_old_orig))
 478                old_orig = &oid_old_orig;
 479        if (!get_oid("HEAD", &oid_orig)) {
 480                orig = &oid_orig;
 481                strbuf_addstr(&msg, "updating ORIG_HEAD");
 482                update_ref(msg.buf, "ORIG_HEAD", orig, old_orig, 0,
 483                           UPDATE_REFS_MSG_ON_ERR);
 484        } else if (old_orig)
 485                delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
 486        strbuf_setlen(&msg, prefix_len);
 487        strbuf_addstr(&msg, "updating HEAD");
 488        if (!switch_to_branch)
 489                ret = update_ref(msg.buf, "HEAD", oid, orig, REF_NO_DEREF,
 490                                 UPDATE_REFS_MSG_ON_ERR);
 491        else {
 492                ret = create_symref("HEAD", switch_to_branch, msg.buf);
 493                if (!ret)
 494                        ret = update_ref(msg.buf, "HEAD", oid, NULL, 0,
 495                                         UPDATE_REFS_MSG_ON_ERR);
 496        }
 497
 498        strbuf_release(&msg);
 499        return ret;
 500}
 501
 502static int rebase_config(const char *var, const char *value, void *data)
 503{
 504        struct rebase_options *opts = data;
 505
 506        if (!strcmp(var, "rebase.stat")) {
 507                if (git_config_bool(var, value))
 508                        opts->flags |= REBASE_DIFFSTAT;
 509                else
 510                        opts->flags &= !REBASE_DIFFSTAT;
 511                return 0;
 512        }
 513
 514        if (!strcmp(var, "rebase.autosquash")) {
 515                opts->autosquash = git_config_bool(var, value);
 516                return 0;
 517        }
 518
 519        if (!strcmp(var, "commit.gpgsign")) {
 520                free(opts->gpg_sign_opt);
 521                opts->gpg_sign_opt = git_config_bool(var, value) ?
 522                        xstrdup("-S") : NULL;
 523                return 0;
 524        }
 525
 526        if (!strcmp(var, "rebase.autostash")) {
 527                opts->autostash = git_config_bool(var, value);
 528                return 0;
 529        }
 530
 531        return git_default_config(var, value, data);
 532}
 533
 534/*
 535 * Determines whether the commits in from..to are linear, i.e. contain
 536 * no merge commits. This function *expects* `from` to be an ancestor of
 537 * `to`.
 538 */
 539static int is_linear_history(struct commit *from, struct commit *to)
 540{
 541        while (to && to != from) {
 542                parse_commit(to);
 543                if (!to->parents)
 544                        return 1;
 545                if (to->parents->next)
 546                        return 0;
 547                to = to->parents->item;
 548        }
 549        return 1;
 550}
 551
 552static int can_fast_forward(struct commit *onto, struct object_id *head_oid,
 553                            struct object_id *merge_base)
 554{
 555        struct commit *head = lookup_commit(the_repository, head_oid);
 556        struct commit_list *merge_bases;
 557        int res;
 558
 559        if (!head)
 560                return 0;
 561
 562        merge_bases = get_merge_bases(onto, head);
 563        if (merge_bases && !merge_bases->next) {
 564                oidcpy(merge_base, &merge_bases->item->object.oid);
 565                res = !oidcmp(merge_base, &onto->object.oid);
 566        } else {
 567                oidcpy(merge_base, &null_oid);
 568                res = 0;
 569        }
 570        free_commit_list(merge_bases);
 571        return res && is_linear_history(onto, head);
 572}
 573
 574/* -i followed by -m is still -i */
 575static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
 576{
 577        struct rebase_options *opts = opt->value;
 578
 579        if (!is_interactive(opts))
 580                opts->type = REBASE_MERGE;
 581
 582        return 0;
 583}
 584
 585/* -i followed by -p is still explicitly interactive, but -p alone is not */
 586static int parse_opt_interactive(const struct option *opt, const char *arg,
 587                                 int unset)
 588{
 589        struct rebase_options *opts = opt->value;
 590
 591        opts->type = REBASE_INTERACTIVE;
 592        opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
 593
 594        return 0;
 595}
 596
 597int cmd_rebase(int argc, const char **argv, const char *prefix)
 598{
 599        struct rebase_options options = {
 600                .type = REBASE_UNSPECIFIED,
 601                .flags = REBASE_NO_QUIET,
 602                .git_am_opt = STRBUF_INIT,
 603                .allow_rerere_autoupdate  = -1,
 604                .allow_empty_message = 1,
 605        };
 606        const char *branch_name;
 607        int ret, flags, total_argc, in_progress = 0;
 608        int ok_to_skip_pre_rebase = 0;
 609        struct strbuf msg = STRBUF_INIT;
 610        struct strbuf revisions = STRBUF_INIT;
 611        struct strbuf buf = STRBUF_INIT;
 612        struct object_id merge_base;
 613        enum {
 614                NO_ACTION,
 615                ACTION_CONTINUE,
 616                ACTION_SKIP,
 617                ACTION_ABORT,
 618                ACTION_QUIT,
 619                ACTION_EDIT_TODO,
 620                ACTION_SHOW_CURRENT_PATCH,
 621        } action = NO_ACTION;
 622        int committer_date_is_author_date = 0;
 623        int ignore_date = 0;
 624        int ignore_whitespace = 0;
 625        const char *gpg_sign = NULL;
 626        int opt_c = -1;
 627        struct string_list whitespace = STRING_LIST_INIT_NODUP;
 628        struct string_list exec = STRING_LIST_INIT_NODUP;
 629        struct option builtin_rebase_options[] = {
 630                OPT_STRING(0, "onto", &options.onto_name,
 631                           N_("revision"),
 632                           N_("rebase onto given branch instead of upstream")),
 633                OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
 634                         N_("allow pre-rebase hook to run")),
 635                OPT_NEGBIT('q', "quiet", &options.flags,
 636                           N_("be quiet. implies --no-stat"),
 637                           REBASE_NO_QUIET| REBASE_VERBOSE | REBASE_DIFFSTAT),
 638                OPT_BIT('v', "verbose", &options.flags,
 639                        N_("display a diffstat of what changed upstream"),
 640                        REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
 641                {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
 642                        N_("do not show diffstat of what changed upstream"),
 643                        PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
 644                OPT_BOOL(0, "ignore-whitespace", &ignore_whitespace,
 645                         N_("passed to 'git apply'")),
 646                OPT_BOOL(0, "signoff", &options.signoff,
 647                         N_("add a Signed-off-by: line to each commit")),
 648                OPT_BOOL(0, "committer-date-is-author-date",
 649                         &committer_date_is_author_date,
 650                         N_("passed to 'git am'")),
 651                OPT_BOOL(0, "ignore-date", &ignore_date,
 652                         N_("passed to 'git am'")),
 653                OPT_BIT('f', "force-rebase", &options.flags,
 654                        N_("cherry-pick all commits, even if unchanged"),
 655                        REBASE_FORCE),
 656                OPT_BIT(0, "no-ff", &options.flags,
 657                        N_("cherry-pick all commits, even if unchanged"),
 658                        REBASE_FORCE),
 659                OPT_CMDMODE(0, "continue", &action, N_("continue"),
 660                            ACTION_CONTINUE),
 661                OPT_CMDMODE(0, "skip", &action,
 662                            N_("skip current patch and continue"), ACTION_SKIP),
 663                OPT_CMDMODE(0, "abort", &action,
 664                            N_("abort and check out the original branch"),
 665                            ACTION_ABORT),
 666                OPT_CMDMODE(0, "quit", &action,
 667                            N_("abort but keep HEAD where it is"), ACTION_QUIT),
 668                OPT_CMDMODE(0, "edit-todo", &action, N_("edit the todo list "
 669                            "during an interactive rebase"), ACTION_EDIT_TODO),
 670                OPT_CMDMODE(0, "show-current-patch", &action,
 671                            N_("show the patch file being applied or merged"),
 672                            ACTION_SHOW_CURRENT_PATCH),
 673                { OPTION_CALLBACK, 'm', "merge", &options, NULL,
 674                        N_("use merging strategies to rebase"),
 675                        PARSE_OPT_NOARG | PARSE_OPT_NONEG,
 676                        parse_opt_merge },
 677                { OPTION_CALLBACK, 'i', "interactive", &options, NULL,
 678                        N_("let the user edit the list of commits to rebase"),
 679                        PARSE_OPT_NOARG | PARSE_OPT_NONEG,
 680                        parse_opt_interactive },
 681                OPT_SET_INT('p', "preserve-merges", &options.type,
 682                            N_("try to recreate merges instead of ignoring "
 683                               "them"), REBASE_PRESERVE_MERGES),
 684                OPT_BOOL(0, "rerere-autoupdate",
 685                         &options.allow_rerere_autoupdate,
 686                         N_("allow rerere to update index  with resolved "
 687                            "conflict")),
 688                OPT_BOOL('k', "keep-empty", &options.keep_empty,
 689                         N_("preserve empty commits during rebase")),
 690                OPT_BOOL(0, "autosquash", &options.autosquash,
 691                         N_("move commits that begin with "
 692                            "squash!/fixup! under -i")),
 693                { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
 694                        N_("GPG-sign commits"),
 695                        PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
 696                OPT_STRING_LIST(0, "whitespace", &whitespace,
 697                                N_("whitespace"), N_("passed to 'git apply'")),
 698                OPT_SET_INT('C', NULL, &opt_c, N_("passed to 'git apply'"),
 699                            REBASE_AM),
 700                OPT_BOOL(0, "autostash", &options.autostash,
 701                         N_("automatically stash/stash pop before and after")),
 702                OPT_STRING_LIST('x', "exec", &exec, N_("exec"),
 703                                N_("add exec lines after each commit of the "
 704                                   "editable list")),
 705                OPT_BOOL(0, "allow-empty-message",
 706                         &options.allow_empty_message,
 707                         N_("allow rebasing commits with empty messages")),
 708                OPT_END(),
 709        };
 710
 711        /*
 712         * NEEDSWORK: Once the builtin rebase has been tested enough
 713         * and git-legacy-rebase.sh is retired to contrib/, this preamble
 714         * can be removed.
 715         */
 716
 717        if (!use_builtin_rebase()) {
 718                const char *path = mkpath("%s/git-legacy-rebase",
 719                                          git_exec_path());
 720
 721                if (sane_execvp(path, (char **)argv) < 0)
 722                        die_errno(_("could not exec %s"), path);
 723                else
 724                        BUG("sane_execvp() returned???");
 725        }
 726
 727        if (argc == 2 && !strcmp(argv[1], "-h"))
 728                usage_with_options(builtin_rebase_usage,
 729                                   builtin_rebase_options);
 730
 731        prefix = setup_git_directory();
 732        trace_repo_setup(prefix);
 733        setup_work_tree();
 734
 735        git_config(rebase_config, &options);
 736
 737        strbuf_reset(&buf);
 738        strbuf_addf(&buf, "%s/applying", apply_dir());
 739        if(file_exists(buf.buf))
 740                die(_("It looks like 'git am' is in progress. Cannot rebase."));
 741
 742        if (is_directory(apply_dir())) {
 743                options.type = REBASE_AM;
 744                options.state_dir = apply_dir();
 745        } else if (is_directory(merge_dir())) {
 746                strbuf_reset(&buf);
 747                strbuf_addf(&buf, "%s/rewritten", merge_dir());
 748                if (is_directory(buf.buf)) {
 749                        options.type = REBASE_PRESERVE_MERGES;
 750                        options.flags |= REBASE_INTERACTIVE_EXPLICIT;
 751                } else {
 752                        strbuf_reset(&buf);
 753                        strbuf_addf(&buf, "%s/interactive", merge_dir());
 754                        if(file_exists(buf.buf)) {
 755                                options.type = REBASE_INTERACTIVE;
 756                                options.flags |= REBASE_INTERACTIVE_EXPLICIT;
 757                        } else
 758                                options.type = REBASE_MERGE;
 759                }
 760                options.state_dir = merge_dir();
 761        }
 762
 763        if (options.type != REBASE_UNSPECIFIED)
 764                in_progress = 1;
 765
 766        total_argc = argc;
 767        argc = parse_options(argc, argv, prefix,
 768                             builtin_rebase_options,
 769                             builtin_rebase_usage, 0);
 770
 771        if (action != NO_ACTION && total_argc != 2) {
 772                usage_with_options(builtin_rebase_usage,
 773                                   builtin_rebase_options);
 774        }
 775
 776        if (argc > 2)
 777                usage_with_options(builtin_rebase_usage,
 778                                   builtin_rebase_options);
 779
 780        if (action != NO_ACTION && !in_progress)
 781                die(_("No rebase in progress?"));
 782
 783        if (action == ACTION_EDIT_TODO && !is_interactive(&options))
 784                die(_("The --edit-todo action can only be used during "
 785                      "interactive rebase."));
 786
 787        switch (action) {
 788        case ACTION_CONTINUE: {
 789                struct object_id head;
 790                struct lock_file lock_file = LOCK_INIT;
 791                int fd;
 792
 793                options.action = "continue";
 794
 795                /* Sanity check */
 796                if (get_oid("HEAD", &head))
 797                        die(_("Cannot read HEAD"));
 798
 799                fd = hold_locked_index(&lock_file, 0);
 800                if (read_index(the_repository->index) < 0)
 801                        die(_("could not read index"));
 802                refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
 803                              NULL);
 804                if (0 <= fd)
 805                        update_index_if_able(the_repository->index,
 806                                             &lock_file);
 807                rollback_lock_file(&lock_file);
 808
 809                if (has_unstaged_changes(1)) {
 810                        puts(_("You must edit all merge conflicts and then\n"
 811                               "mark them as resolved using git add"));
 812                        exit(1);
 813                }
 814                if (read_basic_state(&options))
 815                        exit(1);
 816                goto run_rebase;
 817        }
 818        case ACTION_SKIP: {
 819                struct string_list merge_rr = STRING_LIST_INIT_DUP;
 820
 821                options.action = "skip";
 822
 823                rerere_clear(&merge_rr);
 824                string_list_clear(&merge_rr, 1);
 825
 826                if (reset_head(NULL, "reset", NULL, 0) < 0)
 827                        die(_("could not discard worktree changes"));
 828                if (read_basic_state(&options))
 829                        exit(1);
 830                goto run_rebase;
 831        }
 832        case ACTION_ABORT: {
 833                struct string_list merge_rr = STRING_LIST_INIT_DUP;
 834                options.action = "abort";
 835
 836                rerere_clear(&merge_rr);
 837                string_list_clear(&merge_rr, 1);
 838
 839                if (read_basic_state(&options))
 840                        exit(1);
 841                if (reset_head(&options.orig_head, "reset",
 842                               options.head_name, 0) < 0)
 843                        die(_("could not move back to %s"),
 844                            oid_to_hex(&options.orig_head));
 845                ret = finish_rebase(&options);
 846                goto cleanup;
 847        }
 848        case ACTION_QUIT: {
 849                strbuf_reset(&buf);
 850                strbuf_addstr(&buf, options.state_dir);
 851                ret = !!remove_dir_recursively(&buf, 0);
 852                if (ret)
 853                        die(_("could not remove '%s'"), options.state_dir);
 854                goto cleanup;
 855        }
 856        case ACTION_EDIT_TODO:
 857                options.action = "edit-todo";
 858                options.dont_finish_rebase = 1;
 859                goto run_rebase;
 860        case ACTION_SHOW_CURRENT_PATCH:
 861                options.action = "show-current-patch";
 862                options.dont_finish_rebase = 1;
 863                goto run_rebase;
 864        case NO_ACTION:
 865                break;
 866        default:
 867                BUG("action: %d", action);
 868        }
 869
 870        /* Make sure no rebase is in progress */
 871        if (in_progress) {
 872                const char *last_slash = strrchr(options.state_dir, '/');
 873                const char *state_dir_base =
 874                        last_slash ? last_slash + 1 : options.state_dir;
 875                const char *cmd_live_rebase =
 876                        "git rebase (--continue | --abort | --skip)";
 877                strbuf_reset(&buf);
 878                strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
 879                die(_("It seems that there is already a %s directory, and\n"
 880                      "I wonder if you are in the middle of another rebase.  "
 881                      "If that is the\n"
 882                      "case, please try\n\t%s\n"
 883                      "If that is not the case, please\n\t%s\n"
 884                      "and run me again.  I am stopping in case you still "
 885                      "have something\n"
 886                      "valuable there.\n"),
 887                    state_dir_base, cmd_live_rebase, buf.buf);
 888        }
 889
 890        if (!(options.flags & REBASE_NO_QUIET))
 891                strbuf_addstr(&options.git_am_opt, " -q");
 892
 893        if (committer_date_is_author_date) {
 894                strbuf_addstr(&options.git_am_opt,
 895                              " --committer-date-is-author-date");
 896                options.flags |= REBASE_FORCE;
 897        }
 898
 899        if (ignore_whitespace)
 900                strbuf_addstr(&options.git_am_opt, " --ignore-whitespace");
 901
 902        if (ignore_date) {
 903                strbuf_addstr(&options.git_am_opt, " --ignore-date");
 904                options.flags |= REBASE_FORCE;
 905        }
 906
 907        if (options.keep_empty)
 908                imply_interactive(&options, "--keep-empty");
 909
 910        if (gpg_sign) {
 911                free(options.gpg_sign_opt);
 912                options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
 913        }
 914
 915        if (opt_c >= 0)
 916                strbuf_addf(&options.git_am_opt, " -C%d", opt_c);
 917
 918        if (whitespace.nr) {
 919                int i;
 920
 921                for (i = 0; i < whitespace.nr; i++) {
 922                        const char *item = whitespace.items[i].string;
 923
 924                        strbuf_addf(&options.git_am_opt, " --whitespace=%s",
 925                                    item);
 926
 927                        if ((!strcmp(item, "fix")) || (!strcmp(item, "strip")))
 928                                options.flags |= REBASE_FORCE;
 929                }
 930        }
 931
 932        if (exec.nr) {
 933                int i;
 934
 935                imply_interactive(&options, "--exec");
 936
 937                strbuf_reset(&buf);
 938                for (i = 0; i < exec.nr; i++)
 939                        strbuf_addf(&buf, "exec %s\n", exec.items[i].string);
 940                options.cmd = xstrdup(buf.buf);
 941        }
 942
 943        switch (options.type) {
 944        case REBASE_MERGE:
 945        case REBASE_INTERACTIVE:
 946        case REBASE_PRESERVE_MERGES:
 947                options.state_dir = merge_dir();
 948                break;
 949        case REBASE_AM:
 950                options.state_dir = apply_dir();
 951                break;
 952        default:
 953                /* the default rebase backend is `--am` */
 954                options.type = REBASE_AM;
 955                options.state_dir = apply_dir();
 956                break;
 957        }
 958
 959        if (options.signoff) {
 960                if (options.type == REBASE_PRESERVE_MERGES)
 961                        die("cannot combine '--signoff' with "
 962                            "'--preserve-merges'");
 963                strbuf_addstr(&options.git_am_opt, " --signoff");
 964                options.flags |= REBASE_FORCE;
 965        }
 966
 967        if (!options.root) {
 968                if (argc < 1)
 969                        die("TODO: handle @{upstream}");
 970                else {
 971                        options.upstream_name = argv[0];
 972                        argc--;
 973                        argv++;
 974                        if (!strcmp(options.upstream_name, "-"))
 975                                options.upstream_name = "@{-1}";
 976                }
 977                options.upstream = peel_committish(options.upstream_name);
 978                if (!options.upstream)
 979                        die(_("invalid upstream '%s'"), options.upstream_name);
 980                options.upstream_arg = options.upstream_name;
 981        } else
 982                die("TODO: upstream for --root");
 983
 984        /* Make sure the branch to rebase onto is valid. */
 985        if (!options.onto_name)
 986                options.onto_name = options.upstream_name;
 987        if (strstr(options.onto_name, "...")) {
 988                if (get_oid_mb(options.onto_name, &merge_base) < 0)
 989                        die(_("'%s': need exactly one merge base"),
 990                            options.onto_name);
 991                options.onto = lookup_commit_or_die(&merge_base,
 992                                                    options.onto_name);
 993        } else {
 994                options.onto = peel_committish(options.onto_name);
 995                if (!options.onto)
 996                        die(_("Does not point to a valid commit '%s'"),
 997                                options.onto_name);
 998        }
 999
1000        /*
1001         * If the branch to rebase is given, that is the branch we will rebase
1002         * branch_name -- branch/commit being rebased, or
1003         *                HEAD (already detached)
1004         * orig_head -- commit object name of tip of the branch before rebasing
1005         * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
1006         */
1007        if (argc == 1) {
1008                /* Is it "rebase other branchname" or "rebase other commit"? */
1009                branch_name = argv[0];
1010                options.switch_to = argv[0];
1011
1012                /* Is it a local branch? */
1013                strbuf_reset(&buf);
1014                strbuf_addf(&buf, "refs/heads/%s", branch_name);
1015                if (!read_ref(buf.buf, &options.orig_head))
1016                        options.head_name = xstrdup(buf.buf);
1017                /* If not is it a valid ref (branch or commit)? */
1018                else if (!get_oid(branch_name, &options.orig_head))
1019                        options.head_name = NULL;
1020                else
1021                        die(_("fatal: no such branch/commit '%s'"),
1022                            branch_name);
1023        } else if (argc == 0) {
1024                /* Do not need to switch branches, we are already on it. */
1025                options.head_name =
1026                        xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
1027                                         &flags));
1028                if (!options.head_name)
1029                        die(_("No such ref: %s"), "HEAD");
1030                if (flags & REF_ISSYMREF) {
1031                        if (!skip_prefix(options.head_name,
1032                                         "refs/heads/", &branch_name))
1033                                branch_name = options.head_name;
1034
1035                } else {
1036                        free(options.head_name);
1037                        options.head_name = NULL;
1038                        branch_name = "HEAD";
1039                }
1040                if (get_oid("HEAD", &options.orig_head))
1041                        die(_("Could not resolve HEAD to a revision"));
1042        } else
1043                BUG("unexpected number of arguments left to parse");
1044
1045        if (read_index(the_repository->index) < 0)
1046                die(_("could not read index"));
1047
1048        if (options.autostash) {
1049                struct lock_file lock_file = LOCK_INIT;
1050                int fd;
1051
1052                fd = hold_locked_index(&lock_file, 0);
1053                refresh_cache(REFRESH_QUIET);
1054                if (0 <= fd)
1055                        update_index_if_able(&the_index, &lock_file);
1056                rollback_lock_file(&lock_file);
1057
1058                if (has_unstaged_changes(0) || has_uncommitted_changes(0)) {
1059                        const char *autostash =
1060                                state_dir_path("autostash", &options);
1061                        struct child_process stash = CHILD_PROCESS_INIT;
1062                        struct object_id oid;
1063                        struct commit *head =
1064                                lookup_commit_reference(the_repository,
1065                                                        &options.orig_head);
1066
1067                        argv_array_pushl(&stash.args,
1068                                         "stash", "create", "autostash", NULL);
1069                        stash.git_cmd = 1;
1070                        stash.no_stdin = 1;
1071                        strbuf_reset(&buf);
1072                        if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
1073                                die(_("Cannot autostash"));
1074                        strbuf_trim_trailing_newline(&buf);
1075                        if (get_oid(buf.buf, &oid))
1076                                die(_("Unexpected stash response: '%s'"),
1077                                    buf.buf);
1078                        strbuf_reset(&buf);
1079                        strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
1080
1081                        if (safe_create_leading_directories_const(autostash))
1082                                die(_("Could not create directory for '%s'"),
1083                                    options.state_dir);
1084                        write_file(autostash, "%s", buf.buf);
1085                        printf(_("Created autostash: %s\n"), buf.buf);
1086                        if (reset_head(&head->object.oid, "reset --hard",
1087                                       NULL, 0) < 0)
1088                                die(_("could not reset --hard"));
1089                        printf(_("HEAD is now at %s"),
1090                               find_unique_abbrev(&head->object.oid,
1091                                                  DEFAULT_ABBREV));
1092                        strbuf_reset(&buf);
1093                        pp_commit_easy(CMIT_FMT_ONELINE, head, &buf);
1094                        if (buf.len > 0)
1095                                printf(" %s", buf.buf);
1096                        putchar('\n');
1097
1098                        if (discard_index(the_repository->index) < 0 ||
1099                                read_index(the_repository->index) < 0)
1100                                die(_("could not read index"));
1101                }
1102        }
1103
1104        if (require_clean_work_tree("rebase",
1105                                    _("Please commit or stash them."), 1, 1)) {
1106                ret = 1;
1107                goto cleanup;
1108        }
1109
1110        /*
1111         * Now we are rebasing commits upstream..orig_head (or with --root,
1112         * everything leading up to orig_head) on top of onto.
1113         */
1114
1115        /*
1116         * Check if we are already based on onto with linear history,
1117         * but this should be done only when upstream and onto are the same
1118         * and if this is not an interactive rebase.
1119         */
1120        if (can_fast_forward(options.onto, &options.orig_head, &merge_base) &&
1121            !is_interactive(&options) && !options.restrict_revision &&
1122            !oidcmp(&options.upstream->object.oid, &options.onto->object.oid)) {
1123                int flag;
1124
1125                if (!(options.flags & REBASE_FORCE)) {
1126                        /* Lazily switch to the target branch if needed... */
1127                        if (options.switch_to) {
1128                                struct object_id oid;
1129
1130                                if (get_oid(options.switch_to, &oid) < 0) {
1131                                        ret = !!error(_("could not parse '%s'"),
1132                                                      options.switch_to);
1133                                        goto cleanup;
1134                                }
1135
1136                                strbuf_reset(&buf);
1137                                strbuf_addf(&buf, "rebase: checkout %s",
1138                                            options.switch_to);
1139                                if (reset_head(&oid, "checkout",
1140                                               options.head_name, 0) < 0) {
1141                                        ret = !!error(_("could not switch to "
1142                                                        "%s"),
1143                                                      options.switch_to);
1144                                        goto cleanup;
1145                                }
1146                        }
1147
1148                        if (!(options.flags & REBASE_NO_QUIET))
1149                                ; /* be quiet */
1150                        else if (!strcmp(branch_name, "HEAD") &&
1151                                 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1152                                puts(_("HEAD is up to date."));
1153                        else
1154                                printf(_("Current branch %s is up to date.\n"),
1155                                       branch_name);
1156                        ret = !!finish_rebase(&options);
1157                        goto cleanup;
1158                } else if (!(options.flags & REBASE_NO_QUIET))
1159                        ; /* be quiet */
1160                else if (!strcmp(branch_name, "HEAD") &&
1161                         resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1162                        puts(_("HEAD is up to date, rebase forced."));
1163                else
1164                        printf(_("Current branch %s is up to date, rebase "
1165                                 "forced.\n"), branch_name);
1166        }
1167
1168        /* If a hook exists, give it a chance to interrupt*/
1169        if (!ok_to_skip_pre_rebase &&
1170            run_hook_le(NULL, "pre-rebase", options.upstream_arg,
1171                        argc ? argv[0] : NULL, NULL))
1172                die(_("The pre-rebase hook refused to rebase."));
1173
1174        if (options.flags & REBASE_DIFFSTAT) {
1175                struct diff_options opts;
1176
1177                if (options.flags & REBASE_VERBOSE)
1178                        printf(_("Changes from %s to %s:\n"),
1179                                oid_to_hex(&merge_base),
1180                                oid_to_hex(&options.onto->object.oid));
1181
1182                /* We want color (if set), but no pager */
1183                diff_setup(&opts);
1184                opts.stat_width = -1; /* use full terminal width */
1185                opts.stat_graph_width = -1; /* respect statGraphWidth config */
1186                opts.output_format |=
1187                        DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1188                opts.detect_rename = DIFF_DETECT_RENAME;
1189                diff_setup_done(&opts);
1190                diff_tree_oid(&merge_base, &options.onto->object.oid,
1191                              "", &opts);
1192                diffcore_std(&opts);
1193                diff_flush(&opts);
1194        }
1195
1196        if (is_interactive(&options))
1197                goto run_rebase;
1198
1199        /* Detach HEAD and reset the tree */
1200        if (options.flags & REBASE_NO_QUIET)
1201                printf(_("First, rewinding head to replay your work on top of "
1202                         "it...\n"));
1203
1204        strbuf_addf(&msg, "rebase: checkout %s", options.onto_name);
1205        if (reset_head(&options.onto->object.oid, "checkout", NULL, 1))
1206                die(_("Could not detach HEAD"));
1207        strbuf_release(&msg);
1208
1209        strbuf_addf(&revisions, "%s..%s",
1210                    options.root ? oid_to_hex(&options.onto->object.oid) :
1211                    (options.restrict_revision ?
1212                     oid_to_hex(&options.restrict_revision->object.oid) :
1213                     oid_to_hex(&options.upstream->object.oid)),
1214                    oid_to_hex(&options.orig_head));
1215
1216        options.revisions = revisions.buf;
1217
1218run_rebase:
1219        ret = !!run_specific_rebase(&options);
1220
1221cleanup:
1222        strbuf_release(&revisions);
1223        free(options.head_name);
1224        free(options.gpg_sign_opt);
1225        free(options.cmd);
1226        return ret;
1227}