d67df28efc9a9450fca76332183386e0ae38ef97
   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
  25static char const * const builtin_rebase_usage[] = {
  26        N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
  27                "[<upstream>] [<branch>]"),
  28        N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
  29                "--root [<branch>]"),
  30        N_("git rebase --continue | --abort | --skip | --edit-todo"),
  31        NULL
  32};
  33
  34static GIT_PATH_FUNC(apply_dir, "rebase-apply")
  35static GIT_PATH_FUNC(merge_dir, "rebase-merge")
  36
  37enum rebase_type {
  38        REBASE_UNSPECIFIED = -1,
  39        REBASE_AM,
  40        REBASE_MERGE,
  41        REBASE_INTERACTIVE,
  42        REBASE_PRESERVE_MERGES
  43};
  44
  45static int use_builtin_rebase(void)
  46{
  47        struct child_process cp = CHILD_PROCESS_INIT;
  48        struct strbuf out = STRBUF_INIT;
  49        int ret;
  50
  51        argv_array_pushl(&cp.args,
  52                         "config", "--bool", "rebase.usebuiltin", NULL);
  53        cp.git_cmd = 1;
  54        if (capture_command(&cp, &out, 6)) {
  55                strbuf_release(&out);
  56                return 0;
  57        }
  58
  59        strbuf_trim(&out);
  60        ret = !strcmp("true", out.buf);
  61        strbuf_release(&out);
  62        return ret;
  63}
  64
  65static int apply_autostash(void)
  66{
  67        warning("TODO");
  68        return 0;
  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        int root;
  83        struct commit *restrict_revision;
  84        int dont_finish_rebase;
  85        enum {
  86                REBASE_NO_QUIET = 1<<0,
  87                REBASE_VERBOSE = 1<<1,
  88                REBASE_DIFFSTAT = 1<<2,
  89        } flags;
  90        struct strbuf git_am_opt;
  91};
  92
  93static int is_interactive(struct rebase_options *opts)
  94{
  95        return opts->type == REBASE_INTERACTIVE ||
  96                opts->type == REBASE_PRESERVE_MERGES;
  97}
  98
  99/* Returns the filename prefixed by the state_dir */
 100static const char *state_dir_path(const char *filename, struct rebase_options *opts)
 101{
 102        static struct strbuf path = STRBUF_INIT;
 103        static size_t prefix_len;
 104
 105        if (!prefix_len) {
 106                strbuf_addf(&path, "%s/", opts->state_dir);
 107                prefix_len = path.len;
 108        }
 109
 110        strbuf_setlen(&path, prefix_len);
 111        strbuf_addstr(&path, filename);
 112        return path.buf;
 113}
 114
 115static int finish_rebase(struct rebase_options *opts)
 116{
 117        struct strbuf dir = STRBUF_INIT;
 118        const char *argv_gc_auto[] = { "gc", "--auto", NULL };
 119
 120        delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
 121        apply_autostash();
 122        close_all_packs(the_repository->objects);
 123        /*
 124         * We ignore errors in 'gc --auto', since the
 125         * user should see them.
 126         */
 127        run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
 128        strbuf_addstr(&dir, opts->state_dir);
 129        remove_dir_recursively(&dir, 0);
 130        strbuf_release(&dir);
 131
 132        return 0;
 133}
 134
 135static struct commit *peel_committish(const char *name)
 136{
 137        struct object *obj;
 138        struct object_id oid;
 139
 140        if (get_oid(name, &oid))
 141                return NULL;
 142        obj = parse_object(the_repository, &oid);
 143        return (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
 144}
 145
 146static void add_var(struct strbuf *buf, const char *name, const char *value)
 147{
 148        if (!value)
 149                strbuf_addf(buf, "unset %s; ", name);
 150        else {
 151                strbuf_addf(buf, "%s=", name);
 152                sq_quote_buf(buf, value);
 153                strbuf_addstr(buf, "; ");
 154        }
 155}
 156
 157static int run_specific_rebase(struct rebase_options *opts)
 158{
 159        const char *argv[] = { NULL, NULL };
 160        struct strbuf script_snippet = STRBUF_INIT;
 161        int status;
 162        const char *backend, *backend_func;
 163
 164        add_var(&script_snippet, "GIT_DIR", absolute_path(get_git_dir()));
 165        add_var(&script_snippet, "state_dir", opts->state_dir);
 166
 167        add_var(&script_snippet, "upstream_name", opts->upstream_name);
 168        add_var(&script_snippet, "upstream",
 169                                 oid_to_hex(&opts->upstream->object.oid));
 170        add_var(&script_snippet, "head_name", opts->head_name);
 171        add_var(&script_snippet, "orig_head", oid_to_hex(&opts->orig_head));
 172        add_var(&script_snippet, "onto", oid_to_hex(&opts->onto->object.oid));
 173        add_var(&script_snippet, "onto_name", opts->onto_name);
 174        add_var(&script_snippet, "revisions", opts->revisions);
 175        add_var(&script_snippet, "restrict_revision", opts->restrict_revision ?
 176                oid_to_hex(&opts->restrict_revision->object.oid) : NULL);
 177        add_var(&script_snippet, "GIT_QUIET",
 178                opts->flags & REBASE_NO_QUIET ? "" : "t");
 179        add_var(&script_snippet, "git_am_opt", opts->git_am_opt.buf);
 180        add_var(&script_snippet, "verbose",
 181                opts->flags & REBASE_VERBOSE ? "t" : "");
 182        add_var(&script_snippet, "diffstat",
 183                opts->flags & REBASE_DIFFSTAT ? "t" : "");
 184
 185        switch (opts->type) {
 186        case REBASE_AM:
 187                backend = "git-rebase--am";
 188                backend_func = "git_rebase__am";
 189                break;
 190        case REBASE_INTERACTIVE:
 191                backend = "git-rebase--interactive";
 192                backend_func = "git_rebase__interactive";
 193                break;
 194        case REBASE_MERGE:
 195                backend = "git-rebase--merge";
 196                backend_func = "git_rebase__merge";
 197                break;
 198        case REBASE_PRESERVE_MERGES:
 199                backend = "git-rebase--preserve-merges";
 200                backend_func = "git_rebase__preserve_merges";
 201                break;
 202        default:
 203                BUG("Unhandled rebase type %d", opts->type);
 204                break;
 205        }
 206
 207        strbuf_addf(&script_snippet,
 208                    ". git-sh-setup && . git-rebase--common &&"
 209                    " . %s && %s", backend, backend_func);
 210        argv[0] = script_snippet.buf;
 211
 212        status = run_command_v_opt(argv, RUN_USING_SHELL);
 213        if (opts->dont_finish_rebase)
 214                ; /* do nothing */
 215        else if (status == 0) {
 216                if (!file_exists(state_dir_path("stopped-sha", opts)))
 217                        finish_rebase(opts);
 218        } else if (status == 2) {
 219                struct strbuf dir = STRBUF_INIT;
 220
 221                apply_autostash();
 222                strbuf_addstr(&dir, opts->state_dir);
 223                remove_dir_recursively(&dir, 0);
 224                strbuf_release(&dir);
 225                die("Nothing to do");
 226        }
 227
 228        strbuf_release(&script_snippet);
 229
 230        return status ? -1 : 0;
 231}
 232
 233#define GIT_REFLOG_ACTION_ENVIRONMENT "GIT_REFLOG_ACTION"
 234
 235static int reset_head(struct object_id *oid, const char *action,
 236                      const char *switch_to_branch, int detach_head)
 237{
 238        struct object_id head_oid;
 239        struct tree_desc desc;
 240        struct lock_file lock = LOCK_INIT;
 241        struct unpack_trees_options unpack_tree_opts;
 242        struct tree *tree;
 243        const char *reflog_action;
 244        struct strbuf msg = STRBUF_INIT;
 245        size_t prefix_len;
 246        struct object_id *orig = NULL, oid_orig,
 247                *old_orig = NULL, oid_old_orig;
 248        int ret = 0;
 249
 250        if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
 251                return -1;
 252
 253        if (!oid) {
 254                if (get_oid("HEAD", &head_oid)) {
 255                        rollback_lock_file(&lock);
 256                        return error(_("could not determine HEAD revision"));
 257                }
 258                oid = &head_oid;
 259        }
 260
 261        memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
 262        setup_unpack_trees_porcelain(&unpack_tree_opts, action);
 263        unpack_tree_opts.head_idx = 1;
 264        unpack_tree_opts.src_index = the_repository->index;
 265        unpack_tree_opts.dst_index = the_repository->index;
 266        unpack_tree_opts.fn = oneway_merge;
 267        unpack_tree_opts.update = 1;
 268        unpack_tree_opts.merge = 1;
 269        if (!detach_head)
 270                unpack_tree_opts.reset = 1;
 271
 272        if (read_index_unmerged(the_repository->index) < 0) {
 273                rollback_lock_file(&lock);
 274                return error(_("could not read index"));
 275        }
 276
 277        if (!fill_tree_descriptor(&desc, oid)) {
 278                error(_("failed to find tree of %s"), oid_to_hex(oid));
 279                rollback_lock_file(&lock);
 280                free((void *)desc.buffer);
 281                return -1;
 282        }
 283
 284        if (unpack_trees(1, &desc, &unpack_tree_opts)) {
 285                rollback_lock_file(&lock);
 286                free((void *)desc.buffer);
 287                return -1;
 288        }
 289
 290        tree = parse_tree_indirect(oid);
 291        prime_cache_tree(the_repository->index, tree);
 292
 293        if (write_locked_index(the_repository->index, &lock, COMMIT_LOCK) < 0)
 294                ret = error(_("could not write index"));
 295        free((void *)desc.buffer);
 296
 297        if (ret)
 298                return ret;
 299
 300        reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
 301        strbuf_addf(&msg, "%s: ", reflog_action ? reflog_action : "rebase");
 302        prefix_len = msg.len;
 303
 304        if (!get_oid("ORIG_HEAD", &oid_old_orig))
 305                old_orig = &oid_old_orig;
 306        if (!get_oid("HEAD", &oid_orig)) {
 307                orig = &oid_orig;
 308                strbuf_addstr(&msg, "updating ORIG_HEAD");
 309                update_ref(msg.buf, "ORIG_HEAD", orig, old_orig, 0,
 310                           UPDATE_REFS_MSG_ON_ERR);
 311        } else if (old_orig)
 312                delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
 313        strbuf_setlen(&msg, prefix_len);
 314        strbuf_addstr(&msg, "updating HEAD");
 315        if (!switch_to_branch)
 316                ret = update_ref(msg.buf, "HEAD", oid, orig, REF_NO_DEREF,
 317                                 UPDATE_REFS_MSG_ON_ERR);
 318        else {
 319                ret = create_symref("HEAD", switch_to_branch, msg.buf);
 320                if (!ret)
 321                        ret = update_ref(msg.buf, "HEAD", oid, NULL, 0,
 322                                         UPDATE_REFS_MSG_ON_ERR);
 323        }
 324
 325        strbuf_release(&msg);
 326        return ret;
 327}
 328
 329static int rebase_config(const char *var, const char *value, void *data)
 330{
 331        struct rebase_options *opts = data;
 332
 333        if (!strcmp(var, "rebase.stat")) {
 334                if (git_config_bool(var, value))
 335                        opts->flags |= REBASE_DIFFSTAT;
 336                else
 337                        opts->flags &= !REBASE_DIFFSTAT;
 338                return 0;
 339        }
 340
 341        return git_default_config(var, value, data);
 342}
 343
 344/*
 345 * Determines whether the commits in from..to are linear, i.e. contain
 346 * no merge commits. This function *expects* `from` to be an ancestor of
 347 * `to`.
 348 */
 349static int is_linear_history(struct commit *from, struct commit *to)
 350{
 351        while (to && to != from) {
 352                parse_commit(to);
 353                if (!to->parents)
 354                        return 1;
 355                if (to->parents->next)
 356                        return 0;
 357                to = to->parents->item;
 358        }
 359        return 1;
 360}
 361
 362static int can_fast_forward(struct commit *onto, struct object_id *head_oid,
 363                            struct object_id *merge_base)
 364{
 365        struct commit *head = lookup_commit(the_repository, head_oid);
 366        struct commit_list *merge_bases;
 367        int res;
 368
 369        if (!head)
 370                return 0;
 371
 372        merge_bases = get_merge_bases(onto, head);
 373        if (merge_bases && !merge_bases->next) {
 374                oidcpy(merge_base, &merge_bases->item->object.oid);
 375                res = !oidcmp(merge_base, &onto->object.oid);
 376        } else {
 377                oidcpy(merge_base, &null_oid);
 378                res = 0;
 379        }
 380        free_commit_list(merge_bases);
 381        return res && is_linear_history(onto, head);
 382}
 383
 384int cmd_rebase(int argc, const char **argv, const char *prefix)
 385{
 386        struct rebase_options options = {
 387                .type = REBASE_UNSPECIFIED,
 388                .flags = REBASE_NO_QUIET,
 389                .git_am_opt = STRBUF_INIT,
 390        };
 391        const char *branch_name;
 392        int ret, flags;
 393        int ok_to_skip_pre_rebase = 0;
 394        struct strbuf msg = STRBUF_INIT;
 395        struct strbuf revisions = STRBUF_INIT;
 396        struct object_id merge_base;
 397        struct option builtin_rebase_options[] = {
 398                OPT_STRING(0, "onto", &options.onto_name,
 399                           N_("revision"),
 400                           N_("rebase onto given branch instead of upstream")),
 401                OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
 402                         N_("allow pre-rebase hook to run")),
 403                OPT_NEGBIT('q', "quiet", &options.flags,
 404                           N_("be quiet. implies --no-stat"),
 405                           REBASE_NO_QUIET| REBASE_VERBOSE | REBASE_DIFFSTAT),
 406                OPT_BIT('v', "verbose", &options.flags,
 407                        N_("display a diffstat of what changed upstream"),
 408                        REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
 409                {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
 410                        N_("do not show diffstat of what changed upstream"),
 411                        PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
 412                OPT_END(),
 413        };
 414
 415        /*
 416         * NEEDSWORK: Once the builtin rebase has been tested enough
 417         * and git-legacy-rebase.sh is retired to contrib/, this preamble
 418         * can be removed.
 419         */
 420
 421        if (!use_builtin_rebase()) {
 422                const char *path = mkpath("%s/git-legacy-rebase",
 423                                          git_exec_path());
 424
 425                if (sane_execvp(path, (char **)argv) < 0)
 426                        die_errno(_("could not exec %s"), path);
 427                else
 428                        BUG("sane_execvp() returned???");
 429        }
 430
 431        if (argc == 2 && !strcmp(argv[1], "-h"))
 432                usage_with_options(builtin_rebase_usage,
 433                                   builtin_rebase_options);
 434
 435        prefix = setup_git_directory();
 436        trace_repo_setup(prefix);
 437        setup_work_tree();
 438
 439        git_config(rebase_config, &options);
 440
 441        argc = parse_options(argc, argv, prefix,
 442                             builtin_rebase_options,
 443                             builtin_rebase_usage, 0);
 444
 445        if (argc > 2)
 446                usage_with_options(builtin_rebase_usage,
 447                                   builtin_rebase_options);
 448
 449        if (!(options.flags & REBASE_NO_QUIET))
 450                strbuf_addstr(&options.git_am_opt, " -q");
 451
 452        switch (options.type) {
 453        case REBASE_MERGE:
 454        case REBASE_INTERACTIVE:
 455        case REBASE_PRESERVE_MERGES:
 456                options.state_dir = merge_dir();
 457                break;
 458        case REBASE_AM:
 459                options.state_dir = apply_dir();
 460                break;
 461        default:
 462                /* the default rebase backend is `--am` */
 463                options.type = REBASE_AM;
 464                options.state_dir = apply_dir();
 465                break;
 466        }
 467
 468        if (!options.root) {
 469                if (argc < 1)
 470                        die("TODO: handle @{upstream}");
 471                else {
 472                        options.upstream_name = argv[0];
 473                        argc--;
 474                        argv++;
 475                        if (!strcmp(options.upstream_name, "-"))
 476                                options.upstream_name = "@{-1}";
 477                }
 478                options.upstream = peel_committish(options.upstream_name);
 479                if (!options.upstream)
 480                        die(_("invalid upstream '%s'"), options.upstream_name);
 481                options.upstream_arg = options.upstream_name;
 482        } else
 483                die("TODO: upstream for --root");
 484
 485        /* Make sure the branch to rebase onto is valid. */
 486        if (!options.onto_name)
 487                options.onto_name = options.upstream_name;
 488        if (strstr(options.onto_name, "...")) {
 489                if (get_oid_mb(options.onto_name, &merge_base) < 0)
 490                        die(_("'%s': need exactly one merge base"),
 491                            options.onto_name);
 492                options.onto = lookup_commit_or_die(&merge_base,
 493                                                    options.onto_name);
 494        } else {
 495                options.onto = peel_committish(options.onto_name);
 496                if (!options.onto)
 497                        die(_("Does not point to a valid commit '%s'"),
 498                                options.onto_name);
 499        }
 500
 501        /*
 502         * If the branch to rebase is given, that is the branch we will rebase
 503         * branch_name -- branch/commit being rebased, or
 504         *                HEAD (already detached)
 505         * orig_head -- commit object name of tip of the branch before rebasing
 506         * head_name -- refs/heads/<that-branch> or "detached HEAD"
 507         */
 508        if (argc > 0)
 509                 die("TODO: handle switch_to");
 510        else {
 511                /* Do not need to switch branches, we are already on it. */
 512                options.head_name =
 513                        xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
 514                                         &flags));
 515                if (!options.head_name)
 516                        die(_("No such ref: %s"), "HEAD");
 517                if (flags & REF_ISSYMREF) {
 518                        if (!skip_prefix(options.head_name,
 519                                         "refs/heads/", &branch_name))
 520                                branch_name = options.head_name;
 521
 522                } else {
 523                        options.head_name = xstrdup("detached HEAD");
 524                        branch_name = "HEAD";
 525                }
 526                if (get_oid("HEAD", &options.orig_head))
 527                        die(_("Could not resolve HEAD to a revision"));
 528        }
 529
 530        if (read_index(the_repository->index) < 0)
 531                die(_("could not read index"));
 532
 533        if (require_clean_work_tree("rebase",
 534                                    _("Please commit or stash them."), 1, 1)) {
 535                ret = 1;
 536                goto cleanup;
 537        }
 538
 539        /*
 540         * Now we are rebasing commits upstream..orig_head (or with --root,
 541         * everything leading up to orig_head) on top of onto.
 542         */
 543
 544        /*
 545         * Check if we are already based on onto with linear history,
 546         * but this should be done only when upstream and onto are the same
 547         * and if this is not an interactive rebase.
 548         */
 549        if (can_fast_forward(options.onto, &options.orig_head, &merge_base) &&
 550            !is_interactive(&options) && !options.restrict_revision &&
 551            !oidcmp(&options.upstream->object.oid, &options.onto->object.oid)) {
 552                int flag;
 553
 554                if (!(options.flags & REBASE_NO_QUIET))
 555                        ; /* be quiet */
 556                else if (!strcmp(branch_name, "HEAD") &&
 557                         resolve_ref_unsafe("HEAD", 0, NULL, &flag))
 558                        puts(_("HEAD is up to date, rebase forced."));
 559                else
 560                        printf(_("Current branch %s is up to date, rebase "
 561                                 "forced.\n"), branch_name);
 562        }
 563
 564        /* If a hook exists, give it a chance to interrupt*/
 565        if (!ok_to_skip_pre_rebase &&
 566            run_hook_le(NULL, "pre-rebase", options.upstream_arg,
 567                        argc ? argv[0] : NULL, NULL))
 568                die(_("The pre-rebase hook refused to rebase."));
 569
 570        if (options.flags & REBASE_DIFFSTAT) {
 571                struct diff_options opts;
 572
 573                if (options.flags & REBASE_VERBOSE)
 574                        printf(_("Changes from %s to %s:\n"),
 575                                oid_to_hex(&merge_base),
 576                                oid_to_hex(&options.onto->object.oid));
 577
 578                /* We want color (if set), but no pager */
 579                diff_setup(&opts);
 580                opts.stat_width = -1; /* use full terminal width */
 581                opts.stat_graph_width = -1; /* respect statGraphWidth config */
 582                opts.output_format |=
 583                        DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
 584                opts.detect_rename = DIFF_DETECT_RENAME;
 585                diff_setup_done(&opts);
 586                diff_tree_oid(&merge_base, &options.onto->object.oid,
 587                              "", &opts);
 588                diffcore_std(&opts);
 589                diff_flush(&opts);
 590        }
 591
 592        /* Detach HEAD and reset the tree */
 593        if (options.flags & REBASE_NO_QUIET)
 594                printf(_("First, rewinding head to replay your work on top of "
 595                         "it...\n"));
 596
 597        strbuf_addf(&msg, "rebase: checkout %s", options.onto_name);
 598        if (reset_head(&options.onto->object.oid, "checkout", NULL, 1))
 599                die(_("Could not detach HEAD"));
 600        strbuf_release(&msg);
 601
 602        strbuf_addf(&revisions, "%s..%s",
 603                    options.root ? oid_to_hex(&options.onto->object.oid) :
 604                    (options.restrict_revision ?
 605                     oid_to_hex(&options.restrict_revision->object.oid) :
 606                     oid_to_hex(&options.upstream->object.oid)),
 607                    oid_to_hex(&options.orig_head));
 608
 609        options.revisions = revisions.buf;
 610
 611        ret = !!run_specific_rebase(&options);
 612
 613cleanup:
 614        strbuf_release(&revisions);
 615        free(options.head_name);
 616        return ret;
 617}