Skip to contentSkip to conversation

Introduce git-history(1) command for easy history editing

RFC PATCH Superseded Patrick Steinhardt 13 participants 362 messages Aug 19, 2025 – Feb 5 Page 4 of 4

Subsystems (3)
lore
Share & tools
lore
#294 lore raw

Re: [PATCH v8 7/7] builtin/history: implement "reword" subcommand

In reply to Patrick Steinhardt
Quoted 46 lines · Patrick Steinhardt

Implement a new "reword" subcommand for git-history(1). This subcommand is similar to the user performing an interactive rebase with a single commit changed to use the "reword" instruction.

The "reword" subcommand is built on top of the replay subsystem instead of the sequencer. This leads to some major differences compared to git-rebase(1):

- We do not check out the commit that is to be reworded and instead perform the operation in-memory. This has the obvious benefit of being significantly faster compared to git-rebase(1), but even more importantly it allows the user to rewrite history even if there are local changes in the working tree or in the index.

- We do not execute any hooks, even though we leave some room for changing this in the future.

- By default, all local branches that contain the commit will be rewritten. This especially helps with workflows that use stacked branches.

---
 Documentation/git-history.adoc |  23 ++-
 builtin/history.c              | 392 ++++++++++++++++++++++++++++++++++++++++-
 replay.c                       |   5 +-
 t/meson.build                  |   1 +
 t/t3450-history.sh             |   6 +-
 t/t3451-history-reword.sh      | 344 ++++++++++++++++++++++++++++++++++++
 6 files changed, 758 insertions(+), 13 deletions(-)
Documentation/git-history.adoc +1 -1
index 5a9d931efc..4eea317e5c 100644
@@ -8,7 +8,7 @@ git-history - EXPERIMENTAL: Rewrite history
 SYNOPSIS
 --------
 [synopsis]
-git history [<options>]
+git history reword <commit> [--ref-action=(branches|head|print)]
 
 DESCRIPTION
 -----------

Documentation/git-history.adoc Overall, linkgit:git-history[1] aims to provide a more opinionated way to modify · line 37

Quoted 8 lines
Documentation/git-history.adoc +3 -2
@@ -32,8 +32,9 @@ Overall, linkgit:git-history[1] aims to provide a more opinionated way to modify
 your commit history that is simpler to use compared to linkgit:git-rebase[1] in
 general.
 
-If you want to reapply a range of commits onto a different base, or interactive
-rebases if you want to edit a range of commits.
+Use linkgit:git-rebase[1] if you want to reapply a range of commits onto a
+different base, or interactive rebases if you want to edit a range of commits
+at once.

Ah, was the previous sentence here from the former patch just a bad splitting when you were rewriting?

Documentation/git-history.adoc COMMANDS · line 58

Quoted 10 lines
Documentation/git-history.adoc +4 -0
 LIMITATIONS
 -----------
@@ -51,6 +52,22 @@ COMMANDS
 
 Several commands are available to rewrite history in different ways:
 
+`reword <commit>`::
+       Rewrite the commit message of the specified commit. All the other
+       details of this commit remain unchanged. This command will spawn an
+       editor with the current message of that commit.

One isn't exactly "several"; I know you'll add more later, but since this series ends here, should that word be changed?

Documentation/git-history.adoc COMMANDS · line 66

Quoted 8 lines
Documentation/git-history.adoc +8 -0
+
+OPTIONS
+-------
+
+`--ref-action=(branches|head|print)`::
+       Control which references will be updated by the command, if any. With
+       `branches`, all local branches that point to commits which are
+       decendants of the original commit will be rewritten. With `head`, only

decendants -> descendants . Or maybe double down on the typo and
extend it a bit into either 'decedent' or 'decadent'. That could be fun.

Quoted 132 lines
Documentation/git-history.adoc +4 -0
+       the current `HEAD` reference will be rewritten. With `print`, all
+       updates as they would be performed with `branches` are printed in a
+       format that can be consumed by linkgit:git-update-ref[1].
+
 GIT
 ---
 Part of the linkgit:git[1] suite
builtin/history.c +117 -0
index f6fe32610b..59011ea517 100644
@@ -1,22 +1,404 @@
+#define USE_THE_REPOSITORY_VARIABLE
+
 #include "builtin.h"
+#include "commit.h"
+#include "commit-reach.h"
+#include "config.h"
+#include "editor.h"
+#include "environment.h"
 #include "gettext.h"
+#include "hex.h"
 #include "parse-options.h"
+#include "refs.h"
+#include "replay.h"
+#include "revision.h"
+#include "sequencer.h"
+#include "strvec.h"
+#include "tree.h"
+#include "wt-status.h"
+
+#define GIT_HISTORY_REWORD_USAGE \
+       N_("git history reword <commit> [--ref-action=(branches|head|print)]")
+
+static void change_data_free(void *util, const char *str UNUSED)
+{
+       struct wt_status_change_data *d = util;
+       free(d->rename_source);
+       free(d);
+}
+
+static int fill_commit_message(struct repository *repo,
+                              const struct object_id *old_tree,
+                              const struct object_id *new_tree,
+                              const char *default_message,
+                              const char *action,
+                              struct strbuf *out)
+{
+       const char *path = git_path_commit_editmsg();
+       const char *hint =
+               _("Please enter the commit message for the %s changes."
+                 " Lines starting\nwith '%s' will be ignored, and an"
+                 " empty message aborts the commit.\n");
+       struct wt_status s;
+
+       strbuf_addstr(out, default_message);
+       strbuf_addch(out, '\n');
+       strbuf_commented_addf(out, comment_line_str, hint, action, comment_line_str);
+       write_file_buf(path, out->buf, out->len);
+
+       wt_status_prepare(repo, &s);
+       FREE_AND_NULL(s.branch);
+       s.ahead_behind_flags = AHEAD_BEHIND_QUICK;
+       s.commit_template = 1;
+       s.colopts = 0;
+       s.display_comment_prefix = 1;
+       s.hints = 0;
+       s.use_color = 0;
+       s.whence = FROM_COMMIT;
+       s.committable = 1;
+
+       s.fp = fopen(git_path_commit_editmsg(), "a");
+       if (!s.fp)
+               return error_errno(_("could not open '%s'"), git_path_commit_editmsg());
+
+       wt_status_collect_changes_trees(&s, old_tree, new_tree);
+       wt_status_print(&s);
+       wt_status_collect_free_buffers(&s);
+       string_list_clear_func(&s.change, change_data_free);
+
+       strbuf_reset(out);
+       if (launch_editor(path, out, NULL)) {
+               fprintf(stderr, _("Aborting commit as launching the editor failed.\n"));
+               return -1;
+       }
+       strbuf_stripspace(out, comment_line_str);
+
+       cleanup_message(out, COMMIT_MSG_CLEANUP_ALL, 0);
+
+       if (!out->len) {
+               fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
+               return -1;
+       }
+
+       return 0;
+}
+
+static int commit_tree_with_edited_message(struct repository *repo,
+                                          const char *action,
+                                          struct commit *original,
+                                          struct commit **out)
+{
+       const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
+       const char *original_message, *original_body, *ptr;
+       struct commit_extra_header *original_extra_headers = NULL;
+       struct strbuf commit_message = STRBUF_INIT;
+       struct object_id rewritten_commit_oid;
+       struct object_id original_tree_oid;
+       struct object_id parent_tree_oid;
+       char *original_author = NULL;
+       struct commit *parent;
+       size_t len;
+       int ret;
+
+       original_tree_oid = repo_get_commit_tree(repo, original)->object.oid;
+
+       parent = original->parents ? original->parents->item : NULL;
+       if (parent) {
+               if (repo_parse_commit(repo, parent)) {
+                       ret = error(_("unable to parse parent commit %s"),
+                                   oid_to_hex(&parent->object.oid));
+                       goto out;
+               }
+
+               parent_tree_oid = repo_get_commit_tree(repo, parent)->object.oid;
+       } else {
+               oidcpy(&parent_tree_oid, repo->hash_algo->empty_tree);
+       }
+
+       /* We retain authorship of the original commit. */
+       original_message = repo_logmsg_reencode(repo, original, NULL, NULL);
+       ptr = find_commit_header(original_message, "author", &len);

builtin/history.c line 130

Quoted 10 lines
builtin/history.c +10 -0
+       if (ptr)
+               original_author = xmemdupz(ptr, len);
+       find_commit_subject(original_message, &original_body);
+
+       ret = fill_commit_message(repo, &parent_tree_oid, &original_tree_oid,
+                                 original_body, action, &commit_message);
+       if (ret < 0)
+               goto out;
+
+       original_extra_headers = read_commit_extra_headers(original, exclude_gpgsig);

Does this grab encoding? If so, should it be excluded as well given the repo_logmsg_reencode() call?

Quoted 96 lines
builtin/history.c +96 -0
+
+       ret = commit_tree_extended(commit_message.buf, commit_message.len, &original_tree_oid,
+                                  original->parents, &rewritten_commit_oid, original_author,
+                                  NULL, NULL, original_extra_headers);
+       if (ret < 0)
+               goto out;
+
+       *out = lookup_commit_or_die(&rewritten_commit_oid, "rewritten commit");
+
+out:
+       free_commit_extra_headers(original_extra_headers);
+       strbuf_release(&commit_message);
+       free(original_author);
+       return ret;
+}
+
+enum ref_action {
+       REF_ACTION_DEFAULT,
+       REF_ACTION_BRANCHES,
+       REF_ACTION_HEAD,
+       REF_ACTION_PRINT,
+};
+
+static int parse_ref_action(const struct option *opt, const char *value, int unset)
+{
+       enum ref_action *action = opt->value;
+
+       BUG_ON_OPT_NEG_NOARG(unset, value);
+       if (!strcmp(value, "branches")) {
+               *action = REF_ACTION_BRANCHES;
+       } else if (!strcmp(value, "head")) {
+               *action = REF_ACTION_HEAD;
+       } else if (!strcmp(value, "print")) {
+               *action = REF_ACTION_PRINT;
+       } else {
+               return error(_("%s expects one of 'branches', 'head' or 'print'"),
+                            opt->long_name);
+       }
+
+       return 0;
+}
+
+static int handle_reference_updates(enum ref_action action,
+                                   struct repository *repo,
+                                   struct commit *original,
+                                   struct commit *rewritten,
+                                   const char *reflog_msg)
+{
+       const struct name_decoration *decoration;
+       struct replay_revisions_options opts = { 0 };
+       struct replay_ref_updates updates = {
+               .final_oid = rewritten->object.oid,
+       };
+       struct ref_transaction *transaction = NULL;
+       struct strvec args = STRVEC_INIT;
+       struct strbuf err = STRBUF_INIT;
+       struct commit *head = NULL;
+       struct rev_info revs;
+       char hex[GIT_MAX_HEXSZ + 1];
+       int ret;
+
+       repo_init_revisions(repo, &revs, NULL);
+       strvec_push(&args, "ignored");
+       strvec_push(&args, "--reverse");
+       strvec_push(&args, "--topo-order");
+       strvec_push(&args, "--full-history");
+
+       /* We only want to see commits that are descendants of the old commit. */
+       strvec_pushf(&args, "--ancestry-path=%s",
+                    oid_to_hex(&original->object.oid));
+
+       /*
+        * Ancestry path may also show ancestors of the old commit, but we
+        * don't want to see those, either.
+        */
+       strvec_pushf(&args, "^%s", oid_to_hex(&original->object.oid));
+
+       /*
+        * When we're asked to update HEAD we need to verify that the commit
+        * that we want to rewrite is actually an ancestor of it and, if so,
+        * update it. Otherwise we'll update (or print) all descendant
+        * branches.
+        */
+       if (action == REF_ACTION_HEAD) {
+               struct commit_list *from_list = NULL;
+
+               head = lookup_commit_reference_by_name("HEAD");
+               if (!head) {
+                       ret = error(_("cannot look up HEAD"));
+                       goto out;
+               }
+
+               commit_list_insert(original, &from_list);
+               ret = repo_is_descendant_of(repo, head, from_list);
+               free_commit_list(from_list);
+

builtin/history.c line 236

Quoted 10 lines
builtin/history.c +10 -0
+               if (ret < 0) {
+                       ret = error(_("cannot determine descendance"));
+                       goto out;
+               } else if (!ret) {
+                       ret = error(_("rewritten commit must be an ancestor "
+                                     "of HEAD when using --ref-action=head"));
+                       goto out;
+               }
+
+               strvec_push(&args, oid_to_hex(&head->object.oid));

If you used "HEAD" here instead of its oid, then you wouldn't need a separate codepath for REF_ACTION_HEAD in your "switch(action)" block below.

Quoted 31 lines
builtin/history.c +31 -0
+       } else {
+               strvec_push(&args, "--branches");
+       }
+
+       setup_revisions_from_strvec(&args, &revs, NULL);
+       if (revs.nr)
+               BUG("revisions were set up with invalid argument '%s'", args.v[0]);
+
+       opts.onto = oid_to_hex_r(hex, &rewritten->object.oid);
+
+       ret = replay_revisions(repo, &revs, &opts, &updates);
+       if (ret)
+               goto out;
+
+       switch (action) {
+       case REF_ACTION_DEFAULT:
+       case REF_ACTION_BRANCHES:
+               transaction = ref_store_transaction_begin(get_main_ref_store(repo), 0, &err);
+               if (!transaction) {
+                       ret = error(_("failed to begin ref transaction: %s"), err.buf);
+                       goto out;
+               }
+
+               for (size_t i = 0; i < updates.nr; i++) {
+                       ret = ref_transaction_update(transaction,
+                                                    updates.items[i].refname,
+                                                    &updates.items[i].new_oid,
+                                                    &updates.items[i].old_oid,
+                                                    NULL, NULL, 0, reflog_msg, &err);
+                       if (ret) {
+                               ret = error(_("failed to update ref '%s': %s"),

builtin/history.c line 277

Quoted 10 lines
builtin/history.c +10 -0
+                                           updates.items[i].refname, err.buf);
+                               goto out;
+                       }
+               }
+
+               /*
+                * `replay_revisions()` only updates references that are
+                * ancestors of `rewritten`, so we need to manually
+                * handle updating references that point to `original`.
+                */

This is a good catch; I was wondering if there was a way to put this logic into replay_revisions() so that other callers need not duplicate it, but since it just takes the revisions to walk over and that list is empty, it'd somehow need to know about original->object.oid; it doesn't have that info. Hmmm...

Quoted 22 lines
builtin/history.c +22 -0
+               for (decoration = get_name_decoration(&original->object);
+                    decoration;
+                    decoration = decoration->next)
+               {
+                       if (decoration->type != DECORATION_REF_LOCAL)
+                               continue;
+
+                       ret = ref_transaction_update(transaction,
+                                                    decoration->name,
+                                                    &rewritten->object.oid,
+                                                    &original->object.oid,
+                                                    NULL, NULL, 0, reflog_msg, &err);
+                       if (ret) {
+                               ret = error(_("failed to update ref '%s': %s"),
+                                           decoration->name, err.buf);
+                               goto out;
+                       }
+               }
+
+               if (ref_transaction_commit(transaction, &err)) {
+                       ret = error(_("failed to commit ref transaction: %s"), err.buf);
+                       goto out;

builtin/history.c line 309

Quoted 10 lines
builtin/history.c +10 -0
+               }
+
+               break;
+       case REF_ACTION_HEAD:
+               ret = refs_update_ref(get_main_ref_store(repo), reflog_msg, "HEAD",
+                                     &updates.final_oid, &head->object.oid, 0,
+                                     UPDATE_REFS_MSG_ON_ERR);
+               if (ret)
+                       goto out;
+               break;

As noted above, you wouldn't need this separate REF_ACTION_HEAD block if you passed either "HEAD" or the refname it resolved to instead of passing its oid to the revision range.

Quoted 105 lines
builtin/history.c +81 -5
+       case REF_ACTION_PRINT:
+               for (size_t i = 0; i < updates.nr; i++)
+                       printf("update %s %s %s\n",
+                              updates.items[i].refname,
+                              oid_to_hex(&updates.items[i].new_oid),
+                              oid_to_hex(&updates.items[i].old_oid));
+               break;
+       default:
+               BUG("unsupported ref action %d", action);
+       }
+
+       ret = 0;
+
+out:
+       replay_ref_updates_release(&updates);
+       ref_transaction_free(transaction);
+       release_revisions(&revs);
+       strbuf_release(&err);
+       strvec_clear(&args);
+       return ret;
+}
+
+static int cmd_history_reword(int argc,
+                             const char **argv,
+                             const char *prefix,
+                             struct repository *repo)
+{
+       const char * const usage[] = {
+               GIT_HISTORY_REWORD_USAGE,
+               NULL,
+       };
+       enum ref_action action = REF_ACTION_DEFAULT;
+       struct option options[] = {
+               OPT_CALLBACK_F(0, "ref-action", &action, N_("<action>"),
+                              N_("control ref update behavior (branches|head|print)"),
+                              PARSE_OPT_NONEG, parse_ref_action),
+               OPT_END(),
+       };
+       struct strbuf reflog_msg = STRBUF_INIT;
+       struct commit *original, *rewritten;
+       int ret;
+
+       argc = parse_options(argc, argv, prefix, options, usage, 0);
+       if (argc != 1) {
+               ret = error(_("command expects a single revision"));
+               goto out;
+       }
+       repo_config(repo, git_default_config, NULL);
+
+       original = lookup_commit_reference_by_name(argv[0]);
+       if (!original) {
+               ret = error(_("commit cannot be found: %s"), argv[0]);
+               goto out;
+       }
+
+       ret = commit_tree_with_edited_message(repo, "reworded", original, &rewritten);
+       if (ret < 0) {
+               ret = error(_("failed writing reworded commit"));
+               goto out;
+       }
+
+       strbuf_addf(&reflog_msg, "reword: updating %s", argv[0]);
+
+       ret = handle_reference_updates(action, repo, original, rewritten,
+                                      reflog_msg.buf);
+       if (ret < 0) {
+               ret = error(_("failed replaying descendants"));
+               goto out;
+       }
+
+       ret = 0;
+
+out:
+       strbuf_release(&reflog_msg);
+       return ret;
+}
 
 int cmd_history(int argc,
                const char **argv,
                const char *prefix,
-               struct repository *repo UNUSED)
+               struct repository *repo)
 {
        const char * const usage[] = {
-               N_("git history [<options>]"),
+               GIT_HISTORY_REWORD_USAGE,
                NULL,
        };
+       parse_opt_subcommand_fn *fn = NULL;
        struct option options[] = {
+               OPT_SUBCOMMAND("reword", &fn, cmd_history_reword),
                OPT_END(),
        };
 
        argc = parse_options(argc, argv, prefix, options, usage, 0);
-       if (argc)
-               usagef("unrecognized argument: %s", argv[0]);
-       return 0;
+       return fn(argc, argv, prefix, repo);
 }
replay.c +0 -0
index 8c2f2d3710..5203f9db4c 100644

replay.c int replay_revisions(struct repository *repo, struct rev_info *revs, · line 259

Quoted 7 lines
replay.c +3 -1
@@ -254,7 +254,9 @@ int replay_revisions(struct repository *repo, struct rev_info *revs,
        struct commit *commit;
        struct commit *onto = NULL;
        struct merge_options merge_opt;
-       struct merge_result result;
+       struct merge_result result = {
+               .clean = 1,
+       };

Wait, what? Why is this being initialized this way?

Same as I said over in
https://lore.kernel.org/git/CABPp-BEh7VEM6UQjkK3CxJcv54vEmueTmh9+-SyTKUxgy7Mkcg@mail.gmail.com/,
why is this change here? Was this due to hitting an empty range? Actually, while supporting empty ranges didn't make sense back when I mentioned it to Siddharth (because users always specified the ranges), I think it actually does make sense now that ranges are implicit. Someone could use "git history reword HEAD" (even if "git commit --amend" already exists), and that'd result in an empty range. So, I think the change makes sense now, but I think this particular change really ought to be documented and motivated in a separate commit message rather than lumped in with the other changes in this commit.

replay.c int replay_revisions(struct repository *repo, struct rev_info *revs, · line 273

Quoted 8 lines
replay.c +0 -1
        char *advance;
        int ret;
 
@@ -270,7 +272,6 @@ int replay_revisions(struct repository *repo, struct rev_info *revs,
        }
 
        init_basic_merge_options(&merge_opt, repo);
-       memset(&result, 0, sizeof(result));

And this is related to the new initialization of result, so this change would be part of that separate patch.

Quoted 389 lines
replay.c +0 -0
        merge_opt.show_rename_progress = 0;
        last_commit = onto;
        replayed_commits = kh_init_oid_map();
t/meson.build +1 -0
index 73006b095a..c9f92450dc 100644
@@ -388,6 +388,7 @@ integration_tests = [
   't3437-rebase-fixup-options.sh',
   't3438-rebase-broken-files.sh',
   't3450-history.sh',
+  't3451-history-reword.sh',
   't3500-cherry.sh',
   't3501-revert-cherry-pick.sh',
   't3502-cherry-pick-merge.sh',
t/t3450-history.sh +3 -3
index 417c343d43..f513463b92 100755
@@ -5,13 +5,13 @@ test_description='tests for git-history command'
 . ./test-lib.sh
 
 test_expect_success 'does nothing without any arguments' '
-       git history >out 2>&1 &&
-       test_must_be_empty out
+       test_must_fail git history 2>err &&
+       test_grep "need a subcommand" err
 '
 
 test_expect_success 'raises an error with unknown argument' '
        test_must_fail git history garbage 2>err &&
-       test_grep "unrecognized argument: garbage" err
+       test_grep "unknown subcommand: .garbage." err
 '
 
 test_done
t/t3451-history-reword.sh new file +344 -1
new file mode 100755
index 0000000000..cd5883051d
@@ -0,0 +1,344 @@
+#!/bin/sh
+
+test_description='tests for git-history reword subcommand'
+
+. ./test-lib.sh
+. "$TEST_DIRECTORY/lib-log-graph.sh"
+
+reword_with_message () {
+       cat >message &&
+       write_script fake-editor.sh <<-\EOF &&
+       cp message "$1"
+       EOF
+       test_set_editor "$(pwd)"/fake-editor.sh &&
+       git history reword "$@" &&
+       rm fake-editor.sh message
+}
+
+expect_graph () {
+       cat >expect &&
+       lib_test_cmp_graph --graph --format=%s "$@"
+}
+
+expect_log () {
+       git log --format="%s" "$@" >actual &&
+       cat >expect &&
+       test_cmp expect actual
+}
+
+test_expect_success 'can reword tip of a branch' '
+       test_when_finished "rm -rf repo" &&
+       git init repo &&
+       (
+               cd repo &&
+               test_commit first &&
+               test_commit second &&
+               test_commit third &&
+
+               git symbolic-ref HEAD >expect &&
+               reword_with_message HEAD <<-EOF &&
+               third reworded
+               EOF
+               git symbolic-ref HEAD >actual &&
+               test_cmp expect actual &&
+
+               expect_log <<-\EOF &&
+               third reworded
+               second
+               first
+               EOF
+
+               git reflog >reflog &&
+               test_grep "reword: updating HEAD" reflog
+       )
+'
+
+test_expect_success 'can reword commit in the middle' '
+       test_when_finished "rm -rf repo" &&
+       git init repo &&
+       (
+               cd repo &&
+               test_commit first &&
+               test_commit second &&
+               test_commit third &&
+
+               git symbolic-ref HEAD >expect &&
+               reword_with_message HEAD~ <<-EOF &&
+               second reworded
+               EOF
+               git symbolic-ref HEAD >actual &&
+               test_cmp expect actual &&
+
+               expect_log <<-\EOF
+               third
+               second reworded
+               first
+               EOF
+       )
+'
+
+test_expect_success 'can reword root commit' '
+       test_when_finished "rm -rf repo" &&
+       git init repo &&
+       (
+               cd repo &&
+               test_commit first &&
+               test_commit second &&
+               test_commit third &&
+               reword_with_message HEAD~2 <<-EOF &&
+               first reworded
+               EOF
+
+               expect_log <<-\EOF
+               third
+               second
+               first reworded
+               EOF
+       )
+'
+
+test_expect_success 'can reword in a bare repo' '
+       test_when_finished "rm -rf repo repo.git" &&
+       git init repo &&
+       test_commit -C repo first &&
+       git clone --bare repo repo.git &&
+       (
+               cd repo.git &&
+               reword_with_message HEAD <<-EOF &&
+               reworded
+               EOF
+
+               expect_log <<-\EOF
+               reworded
+               EOF
+       )
+'
+
+test_expect_success 'can reword a commit on a different branch' '
+       test_when_finished "rm -rf repo" &&
+       git init repo &&
+       (
+               cd repo &&
+               test_commit base &&
+               git branch theirs &&
+               test_commit ours &&
+               git switch theirs &&
+               test_commit theirs &&
+
+               git rev-parse ours >ours-before &&
+               reword_with_message theirs <<-EOF &&
+               Reworded theirs
+               EOF
+               git rev-parse ours >ours-after &&
+               test_cmp ours-before ours-after &&
+
+               expect_graph --branches <<-\EOF
+               * Reworded theirs
+               | * ours
+               |/
+               * base
+               EOF
+       )
+'
+
+test_expect_success 'can reword a merge commit' '
+       test_when_finished "rm -rf repo" &&
+       git init repo &&
+       (
+               cd repo &&
+               test_commit base &&
+               git branch branch &&
+               test_commit ours &&
+               git switch branch &&
+               test_commit theirs &&
+               git switch - &&
+               git merge theirs &&
+
+               # It is not possible to replay merge commits embedded in the
+               # history (yet).
+               test_must_fail git history reword HEAD~ 2>err &&
+               test_grep "replaying merge commits is not supported yet" err &&
+
+               # But it is possible to reword a merge commit directly.
+               reword_with_message HEAD <<-EOF &&
+               Reworded merge commit
+               EOF
+               expect_graph <<-\EOF
+               *   Reworded merge commit
+               |\
+               | * theirs
+               * | ours
+               |/
+               * base
+               EOF
+       )
+'
+
+test_expect_success '--ref-action=print prints ref updates without modifying repo' '
+       test_when_finished "rm -rf repo" &&
+       git init repo --initial-branch=main &&
+       (
+               cd repo &&
+               test_commit base &&
+               git branch branch &&
+               test_commit ours &&
+               git switch branch &&
+               test_commit theirs &&
+
+               git refs list >refs-expect &&
+               reword_with_message --ref-action=print base >updates <<-\EOF &&
+               reworded commit
+               EOF
+               git refs list >refs-actual &&
+               test_cmp refs-expect refs-actual &&
+
+               test_grep "update refs/heads/branch" updates &&
+               test_grep "update refs/heads/main" updates &&
+               git update-ref --stdin <updates &&
+               expect_log --branches <<-\EOF
+               theirs
+               ours
+               reworded commit
+               EOF
+       )
+'
+
+test_expect_success '--ref-action=head updates only HEAD' '
+       test_when_finished "rm -rf repo" &&
+       git init repo --initial-branch=main &&
+       (
+               cd repo &&
+               test_commit base &&
+               git branch branch &&
+               test_commit theirs &&
+               git switch branch &&
+               test_commit ours &&
+
+               # When told to update HEAD, only, the command will refuse to
+               # rewrite commits that are not an ancestor of HEAD.
+               test_must_fail git history reword --ref-action=head theirs 2>err &&
+               test_grep "rewritten commit must be an ancestor of HEAD" err &&
+
+               reword_with_message --ref-action=head base >updates <<-\EOF &&
+               reworded base
+               EOF
+               expect_log HEAD <<-\EOF &&
+               ours
+               reworded base
+               EOF
+               expect_log main <<-\EOF
+               theirs
+               base
+               EOF
+       )
+'
+
+test_expect_success 'editor shows proper status' '
+       test_when_finished "rm -rf repo" &&
+       git init repo &&
+       (
+               cd repo &&
+               test_commit first &&
+
+               write_script fake-editor.sh <<-\EOF &&
+               cp "$1" . &&
+               printf "\namend a comment\n" >>"$1"
+               EOF
+               test_set_editor "$(pwd)"/fake-editor.sh &&
+               git history reword HEAD &&
+
+               cat >expect <<-EOF &&
+               first
+
+               # Please enter the commit message for the reworded changes. Lines starting
+               # with ${SQ}#${SQ} will be ignored, and an empty message aborts the commit.
+               # Changes to be committed:
+               #       new file:   first.t
+               #
+               EOF
+               test_cmp expect COMMIT_EDITMSG &&
+
+               test_commit_message HEAD <<-\EOF
+               first
+
+               amend a comment
+               EOF
+       )
+'
+
+# For now, git-history(1) does not yet execute any hooks. This is subject to
+# change in the future, and if it does this test here is expected to start
+# failing. In other words, this test is not an endorsement of the current
+# status quo.
+test_expect_success 'hooks are not executed for rewritten commits' '
+       test_when_finished "rm -rf repo" &&
+       git init repo &&
+       (
+               cd repo &&
+               test_commit first &&
+               test_commit second &&
+               test_commit third &&
+
+               ORIG_PATH="$(pwd)" &&
+               export ORIG_PATH &&
+               for hook in prepare-commit-msg pre-commit post-commit post-rewrite commit-msg
+               do
+                       write_script .git/hooks/$hook <<-\EOF || exit 1
+                       touch "$ORIG_PATH/hooks.log
+                       EOF
+               done &&
+
+               reword_with_message HEAD~ <<-EOF &&
+               second reworded
+               EOF
+
+               cat >expect <<-EOF &&
+               third
+               second reworded
+               first
+               EOF
+               git log --format=%s >actual &&
+               test_cmp expect actual &&
+
+               test_path_is_missing hooks.log
+       )
+'
+
+test_expect_success 'aborts with empty commit message' '
+       test_when_finished "rm -rf repo" &&
+       git init repo &&
+       (
+               cd repo &&
+               test_commit first &&
+
+               ! reword_with_message HEAD 2>err </dev/null &&
+               test_grep "Aborting commit due to empty commit message." err
+       )
+'
+
+test_expect_success 'retains changes in the worktree and index' '
+       test_when_finished "rm -rf repo" &&
+       git init repo &&
+       (
+               cd repo &&
+               touch a b &&
+               git add . &&
+               git commit -m "initial commit" &&
+               echo foo >a &&
+               echo bar >b &&
+               git add b &&
+               reword_with_message HEAD <<-EOF &&
+               message
+               EOF
+               cat >expect <<-\EOF &&
+                M a
+               M  b
+               ?? actual
+               ?? expect
+               EOF
+               git status --porcelain >actual &&
+               test_cmp expect actual
+       )
+'
+
+test_done
 
--

2.52.0.542.g9473a8513b.dirty

#295 lore raw

Re: [PATCH v8 7/7] builtin/history: implement "reword" subcommand

Quoted 18 lines · Elijah Newren
Quoted 17 lines · Patrick Steinhardt
Documentation/git-history.adoc +1 -1
index 5a9d931efc..4eea317e5c 100644
@@ -8,7 +8,7 @@ git-history - EXPERIMENTAL: Rewrite history
 SYNOPSIS
 --------
 [synopsis]
-git history [<options>]
+git history reword <commit> [--ref-action=(branches|head|print)]
 
 DESCRIPTION
 -----------
@@ -32,8 +32,9 @@ Overall, linkgit:git-history[1] aims to provide a more opinionated way to modify
 your commit history that is simpler to use compared to linkgit:git-rebase[1] in
 general.
 
Quoted 8 lines

Documentation/git-history.adoc Overall, linkgit:git-history[1] aims to provide a more opinionated way to modify · line 37

Quoted 5 lines
Documentation/git-history.adoc +3 -2
-If you want to reapply a range of commits onto a different base, or interactive
-rebases if you want to edit a range of commits.
+Use linkgit:git-rebase[1] if you want to reapply a range of commits onto a
+different base, or interactive rebases if you want to edit a range of commits
+at once.

Ah, was the previous sentence here from the former patch just a bad splitting when you were rewriting?

Dunno what happened here, to be honest.

Quoted 6 lines
Quoted 6 lines
Documentation/git-history.adoc +0 -0
 LIMITATIONS
 -----------
@@ -51,6 +52,22 @@ COMMANDS
 
 Several commands are available to rewrite history in different ways:
 
Quoted 7 lines

Documentation/git-history.adoc COMMANDS · line 58

Quoted 4 lines
Documentation/git-history.adoc +4 -0
+`reword <commit>`::
+       Rewrite the commit message of the specified commit. All the other
+       details of this commit remain unchanged. This command will spawn an
+       editor with the current message of that commit.

One isn't exactly "several"; I know you'll add more later, but since this series ends here, should that word be changed?

We can just say "The following commands", there is no need to be specific.

Quoted 4 lines
Quoted 4 lines
Documentation/git-history.adoc +4 -0
+
+OPTIONS
+-------
+
Quoted 8 lines

Documentation/git-history.adoc COMMANDS · line 66

Quoted 4 lines
Documentation/git-history.adoc +4 -0
+`--ref-action=(branches|head|print)`::
+       Control which references will be updated by the command, if any. With
+       `branches`, all local branches that point to commits which are
+       decendants of the original commit will be rewritten. With `head`, only

decendants -> descendants . Or maybe double down on the typo and
extend it a bit into either 'decedent' or 'decadent'. That could be fun.

Thanks, this made me laugh. :)

Quoted 5 lines
Quoted 5 lines
builtin/history.c +0 -0
index f6fe32610b..59011ea517 100644
@@ -1,22 +1,404 @@

[snip]

Quoted 40 lines
Quoted 40 lines
builtin/history.c +40 -0
+static int commit_tree_with_edited_message(struct repository *repo,
+                                          const char *action,
+                                          struct commit *original,
+                                          struct commit **out)
+{
+       const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
+       const char *original_message, *original_body, *ptr;
+       struct commit_extra_header *original_extra_headers = NULL;
+       struct strbuf commit_message = STRBUF_INIT;
+       struct object_id rewritten_commit_oid;
+       struct object_id original_tree_oid;
+       struct object_id parent_tree_oid;
+       char *original_author = NULL;
+       struct commit *parent;
+       size_t len;
+       int ret;
+
+       original_tree_oid = repo_get_commit_tree(repo, original)->object.oid;
+
+       parent = original->parents ? original->parents->item : NULL;
+       if (parent) {
+               if (repo_parse_commit(repo, parent)) {
+                       ret = error(_("unable to parse parent commit %s"),
+                                   oid_to_hex(&parent->object.oid));
+                       goto out;
+               }
+
+               parent_tree_oid = repo_get_commit_tree(repo, parent)->object.oid;
+       } else {
+               oidcpy(&parent_tree_oid, repo->hash_algo->empty_tree);
+       }
+
+       /* We retain authorship of the original commit. */
+       original_message = repo_logmsg_reencode(repo, original, NULL, NULL);
+       ptr = find_commit_header(original_message, "author", &len);
+       if (ptr)
+               original_author = xmemdupz(ptr, len);
+       find_commit_subject(original_message, &original_body);
+
+       ret = fill_commit_message(repo, &parent_tree_oid, &original_tree_oid,
Quoted 8 lines

builtin/history.c line 130

Quoted 5 lines
builtin/history.c +5 -0
+                                 original_body, action, &commit_message);
+       if (ret < 0)
+               goto out;
+
+       original_extra_headers = read_commit_extra_headers(original, exclude_gpgsig);

Does this grab encoding? If so, should it be excluded as well given the repo_logmsg_reencode() call?

Hm, good question indeed. I think that makes sense.

[snip]

Quoted 39 lines
Quoted 39 lines
builtin/history.c +39 -0
+       } else {
+               strvec_push(&args, "--branches");
+       }
+
+       setup_revisions_from_strvec(&args, &revs, NULL);
+       if (revs.nr)
+               BUG("revisions were set up with invalid argument '%s'", args.v[0]);
+
+       opts.onto = oid_to_hex_r(hex, &rewritten->object.oid);
+
+       ret = replay_revisions(repo, &revs, &opts, &updates);
+       if (ret)
+               goto out;
+
+       switch (action) {
+       case REF_ACTION_DEFAULT:
+       case REF_ACTION_BRANCHES:
+               transaction = ref_store_transaction_begin(get_main_ref_store(repo), 0, &err);
+               if (!transaction) {
+                       ret = error(_("failed to begin ref transaction: %s"), err.buf);
+                       goto out;
+               }
+
+               for (size_t i = 0; i < updates.nr; i++) {
+                       ret = ref_transaction_update(transaction,
+                                                    updates.items[i].refname,
+                                                    &updates.items[i].new_oid,
+                                                    &updates.items[i].old_oid,
+                                                    NULL, NULL, 0, reflog_msg, &err);
+                       if (ret) {
+                               ret = error(_("failed to update ref '%s': %s"),
+                                           updates.items[i].refname, err.buf);
+                               goto out;
+                       }
+               }
+
+               /*
+                * `replay_revisions()` only updates references that are
+                * ancestors of `rewritten`, so we need to manually
Quoted 8 lines

builtin/history.c line 277

Quoted 2 lines
builtin/history.c +2 -0
+                * handle updating references that point to `original`.
+                */

This is a good catch; I was wondering if there was a way to put this logic into replay_revisions() so that other callers need not duplicate it, but since it just takes the revisions to walk over and that list is empty, it'd somehow need to know about original->object.oid; it doesn't have that info. Hmmm...

Yeah, exactly. I was also thinking about whether this can be part of git-replay(1), but ultimately it didn't really seem to make sense. After all this is about a commit that we're _not_ replaying at all, but that we have manually edited.

Quoted 15 lines

replay.c int replay_revisions(struct repository *repo, struct rev_info *revs, · line 259

Quoted 12 lines
replay.c +3 -1
index 8c2f2d3710..5203f9db4c 100644
@@ -254,7 +254,9 @@ int replay_revisions(struct repository *repo, struct rev_info *revs,
        struct commit *commit;
        struct commit *onto = NULL;
        struct merge_options merge_opt;
-       struct merge_result result;
+       struct merge_result result = {
+               .clean = 1,
+       };

Wait, what? Why is this being initialized this way?

Quoted 3 lines

Same as I said over in
https://lore.kernel.org/git/CABPp-BEh7VEM6UQjkK3CxJcv54vEmueTmh9+-SyTKUxgy7Mkcg@mail.gmail.com/,
why is this change here? Was this due to hitting an empty range?

Yeah, exactly.

Quoted 8 lines

Actually, while supporting empty ranges didn't make sense back when I mentioned it to Siddharth (because users always specified the ranges), I think it actually does make sense now that ranges are implicit. Someone could use "git history reword HEAD" (even if "git commit --amend" already exists), and that'd result in an empty range. So, I think the change makes sense now, but I think this particular change really ought to be documented and motivated in a separate commit message rather than lumped in with the other changes in this commit.

That's fair, will do.

Thanks!

Patrick

#296 lore raw
In reply to Patrick Steinhardt
Quoted 8 lines · Patrick Steinhardt

Hi,

over recent months I've been playing around with Jujutsu quite frequently. While I still prefer using Git, there's been a couple features in it that I really like and that I'd like to have in Git, as well.

Quoted 5 lines

- I've dropped the patches introducing git history split and will send this as a follow-up patch series once this once has been merged. This was done to focus attention on the underlying mechanics as much as possible (and to keep my own sanity with the frequent revamps).

Sane, if sad for my custom build which has enjoyed having "git history" commands available :) I can wait for other patches, or try to contribute some, though.

[reads further]

Oh, it's just split that drops; we still have reword, etc. Cool!

Quoted 20 lines

Range-diff versus v7:

 -:  ---------- >  1:  53a845e874 builtin/replay: extract core logic to replay revisions
 -:  ---------- >  2:  3ff1c0bacf builtin/replay: move core logic into "libgit.a"
 -:  ---------- >  3:  598df4e186 replay: small set of cleanups
 -:  ---------- >  4:  fd6a0ec5b8 replay: yield the object ID of the final rewritten commit
 1:  0e2d8db69f =  5:  04b832320f wt-status: provide function to expose status for trees
 2:  087c563575 <  -:  ---------- replay: extract logic to pick commits
 3:  4ab2a6f807 <  -:  ---------- replay: stop using `the_repository`
 4:  d2138e95d4 !  6:  e223659b86 builtin: add new "history" command

@@ Commit message

While these operations are all doable, it often feels needlessly kludgey to do so by doing an interactive rebase, using the editor to say what
- one wants, and then perform the actions. Furthermore, some operations
- like splitting up a commit into two are way more involved than that and
+ one wants, and then perform the actions. Also, some operations like
+ splitting up a commit into two are way more involved than that and
require a whole series of commands.

Quoted 3 lines

- Add a new "history" command to plug this gap. This command will have
+ Another problem that rebases have is that dependent branches are not
+ being updated. The use of stacked branches has grown quite common with

"[D]ependent branches are not being updated" reads weirdly to me. "Rebases also do not update dependent branches" perhaps?

Quoted 1 line

+ competiting version control systems like Jujutsu though, so it clearly

"competing" ;)

Quoted 22 lines
    +    is a need that users have. While rebases _can_ serve this use case if
    +    one always works on the latest stacked branch, it is somewhat awkward
    +    and very easy to get wrong.

+
+ Add a new "history" command to plug these gaps. This command will have
several different subcommands to imperatively rewrite history for common
- use cases like the above. Some of these subcommands will be implemented
- in subsequent commits.
+ use cases like the above.

@@ Documentation/git-history.adoc (new)
+
+NAME
+----
-+git-history - EXPERIMENTAL: Rewrite history of the current branch ++git-history - EXPERIMENTAL: Rewrite history
+
+SYNOPSIS
+--------
@@ Documentation/git-history.adoc (new)

[snip]

Quoted 2 lines

++If you want to reapply a range of commits onto a different base, or interactive ++rebases if you want to edit a range of commits.

Hm? This feels incomplete to me.

Best,
Ben

#297 lore raw
Quoted 15 lines · D. Ben Knoble
Quoted 8 lines · Patrick Steinhardt

Hi,

over recent months I've been playing around with Jujutsu quite frequently. While I still prefer using Git, there's been a couple features in it that I really like and that I'd like to have in Git, as well.

Quoted 5 lines

- I've dropped the patches introducing git history split and will send this as a follow-up patch series once this once has been merged. This was done to focus attention on the underlying mechanics as much as possible (and to keep my own sanity with the frequent revamps).

Quoted 6 lines

Sane, if sad for my custom build which has enjoyed having "git history" commands available :) I can wait for other patches, or try to contribute some, though.

[reads further]

Oh, it's just split that drops; we still have reword, etc. Cool!

We only have "reword" for now. In any case, I'll definitely upstream more subcommands once the initial version has landed. Probably the complete set of commands I was proposing initially: "drop", "split" and "reorder". Afterwards I'd also like to have a look at "absorb", but I'll also gladly accept any help.

Quoted 24 lines
Quoted 20 lines

Range-diff versus v7:

 -:  ---------- >  1:  53a845e874 builtin/replay: extract core logic to replay revisions
 -:  ---------- >  2:  3ff1c0bacf builtin/replay: move core logic into "libgit.a"
 -:  ---------- >  3:  598df4e186 replay: small set of cleanups
 -:  ---------- >  4:  fd6a0ec5b8 replay: yield the object ID of the final rewritten commit
 1:  0e2d8db69f =  5:  04b832320f wt-status: provide function to expose status for trees
 2:  087c563575 <  -:  ---------- replay: extract logic to pick commits
 3:  4ab2a6f807 <  -:  ---------- replay: stop using `the_repository`
 4:  d2138e95d4 !  6:  e223659b86 builtin: add new "history" command

@@ Commit message

While these operations are all doable, it often feels needlessly kludgey to do so by doing an interactive rebase, using the editor to say what
- one wants, and then perform the actions. Furthermore, some operations
- like splitting up a commit into two are way more involved than that and
+ one wants, and then perform the actions. Also, some operations like
+ splitting up a commit into two are way more involved than that and
require a whole series of commands.

Quoted 3 lines

- Add a new "history" command to plug this gap. This command will have
+ Another problem that rebases have is that dependent branches are not
+ being updated. The use of stacked branches has grown quite common with

Quoted 6 lines

"[D]ependent branches are not being updated" reads weirdly to me. "Rebases also do not update dependent branches" perhaps?

Quoted 1 line

+ competiting version control systems like Jujutsu though, so it clearly

"competing" ;)

Fixed both, thanks!

Patrick

#298 lore raw
Quoted 6 lines · Patrick Steinhardt

We only have "reword" for now. In any case, I'll definitely upstream more subcommands once the initial version has landed. Probably the complete set of commands I was proposing initially: "drop", "split" and "reorder". Afterwards I'd also like to have a look at "absorb", but I'll also gladly accept any help.

I figured as much. I stumbled onto a version of git-absorb [1] today, and I have some notes on how I might script such a thing myself using my "git-touching" [2] script. But my script has a slight bug [3] when handling staged changes that might make it not quite ready for the attempt yet. Anyway, some food for thought.

[1]: https://github.com/tummychow/git-absorb
[2]: https://github.com/benknoble/Dotfiles/blob/master/links/bin/git-touching
[3]: From my todo list: git: touching -c only considers staged files, not staged lines. So mixed files give the wrong outputs.

Signature · 1 line
D. Ben Knoble
#299 lore raw

v9 cover Introduce git-history(1) command for easy history editing

In reply to Patrick Steinhardt

Hi,

over recent months I've been playing around with Jujutsu quite frequently. While I still prefer using Git, there's been a couple features in it that I really like and that I'd like to have in Git, as well.

A copule of these features relate to history editing. Most importantly, I really dig the following commands:

- jj-abandon(1) to drop a specific commit from your history.

- jj-absorb(1) to take some changes and automatically apply them to commits in your history that last modified the respective hunks.

- jj-split(1) to split a commit into two.

- jj-new(1) to insert a new commit after or before a specific other commit.

Not all of these commands can be ported directly into Git. jj-new(1) for example doesn't really make a ton of sense for us, I'd claim. But some of these commands _do_ make sense.

This patch series is a starting point for such a command. For now, it only implements rewording of commits. I'll continue introducing new commands once this patch series has been merged though.

Changes in v9:
- Rename struct replay_ref_updates to struct replay_result to make
its semantics less focussed on ref updates, only.
- Clarify and fix return codes of git-replay(1) so that we return 1 on
conflict, 128 on an error and 0 on success.
- The usual small improvements to commit messages.
- Link to v8: https://lore.kernel.org/r/[email protected]

Changes in v8:
- The series is now built on top of e0bfec3dfc (The 15th batch,
2026-01-06) with kh/replay-invalid-onto-advance at 56b77a687e
(t3650: add more regression tests for failure conditions,
2026-01-05) merged into it. The latter is expected to hit 'next'
soonish.
- Another biggish revamp to build almost completely on top of the
git-replay(1) logic.
- We now advance all branches descending from the rewritten commit by
default.
- I've dropped the patches introducing git history split and will
send this as a follow-up patch series once this once has been
merged. This was done to focus attention on the underlying mechanics
as much as possible (and to keep my own sanity with the frequent
revamps).
- Link to v7: https://lore.kernel.org/r/[email protected]

Changes in v7:
- I've rebased the patch series on top of f0ef5b6d9b (The fifth batch,

    2025-11-30) with pw/replay-exclude-gpgsig-fix at 9f3a115087 (replay:
    do not copy "gpgsign-sha256" header, 2025-11-26) merged into it to
    fix some conflicts.

- I refactored a bunch of code to be shared between split and reword.
- I am now using "--ancestry-path" and "--reverse" to enumerate
commits.
- git history split now asks for commit messages for both commits.
- git history split no longer allows the user to edit hunks so that
conflicts become impossible. This may be reintroduced at a later
point in time.
- A bunch of test improvements.
- Several commit message and documentation improvements.
- Link to v6: https://lore.kernel.org/r/[email protected]

Changes in v6:
- I've rebased the patch series again to pull in the latest updates from sa/replay-atomic-ref-updates and fix conflicts. It is now based on 4e98b730f1 (The twenty-fourth batch, 2025-10-24) with ab661bb1bb (replay: add replay.refAction config option, 2025-10-23) merged into it.
- I've dropped the "-m" options for now, so commit messages are always asked for via the editor. These can be introduced in a subsequent patch series once discussion around them has settled.
- We don't use the merge machinery anymore to pick the commits.
- Drop the commit to parse commits in the replay machinery. It didn't seem to be necessary in v5 anymore, and now that we don't use the merge machinery at all we don't ever take that code path in the first place.
- Link to v5:

    https://lore.kernel.org/r/[email protected]

Changes in v5:
- I've changed the patch series to be based on top of 133d151831 (The twenty-first batch, 2025-10-20) with sa/replay-atomic-ref-updates at a1c22e627e (SQAUASH??? t0450 band-aid, 2025-10-14) merged into it.
This is one the one hand to fix a conflict, but also to get some of
the CI updates to make GitLab CI work again.
- Some slight commit message improvements.
- Deduplicate subcommand usage strings by using defines.
- Fix the desendancy checks to properly verify that HEAD is a
descendant of the commit to be rewritten. Also add some tests for
this.
- Fix the hint that mentions that lines starting with the comment
character will be tripped after having written the commit message.
- Move an include to the correct commit.
- Link to v4: https://lore.kernel.org/r/[email protected]

Changes in v4:
- I've rebuilt the patch series. It is now based on 821f583da6 (The
thirteenth batcn, 2025-09-29) with sa/replay-atomic-ref-updates
at 665c66a743 (replay: make atomic ref updates the default behavior, 2025-09-27) merged into it. This should fix all conflicts with seen.
- I've reworked this patch series to use the same infra as
git-replay(1), as discussed during the Contributor's Summit.
- I've slimmed down the patch series to only tackle those commands
that cannot result in a conflict to keep it simple. I also learned
that Elijah has been working on a "git replay edit" command, so I
dropped that command so that we can instead use his version.
- During the Contributor's Summit we have agreed that for now, we
won't care about hook execution just yet. This may be backfilled at
a later point in time.
- I dropped "commit.verbose" handling for now, as my understanding of
it was wrong at first. This is something we should backfill.
- Link to v3: https://lore.kernel.org/r/[email protected]

Changes in v3:
- Add logic to drive the "post-rewrite" hook and add tests to verify
that all hooks are executed as expected.
- Deduplicate logic to turn a replay action into a todo command.
- Move the addition of tests for the top-level git-history(1) command
to the correct commit.
- Some smaller commit message fixes.
- Honor "commit.verbose".
- Fix copy-paste error with an error message.
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- Add a new "reword" subcommand.
- List git-history(1) in "command-list.txt".
- Add some missing error handling.
- Simplify calling convention of apply_commits() to handle root
commits internally instead of requiring every caller to do so.
- Add tests to verify that git-history(1) refuses to work with changes
in the worktree or index.
- Mark git-history(1) as experimental.
- Introduce commands to manage interrupted history edits.
- A bunch of improvements to the manpage.
- Link to v1: https://lore.kernel.org/r/[email protected]

Thanks!

Patrick

---
Patrick Steinhardt (7):
builtin/replay: extract core logic to replay revisions builtin/replay: move core logic into "libgit.a"
replay: small set of cleanups
replay: yield the object ID of the final rewritten commit
wt-status: provide function to expose status for trees
builtin: add new "history" command builtin/history: implement "reword" subcommand

 .gitignore                     |   1 +
 Documentation/git-history.adoc |  73 ++++++++
 Documentation/meson.build      |   1 +
 Makefile                       |   2 +
 builtin.h                      |   1 +
 builtin/history.c              | 404 +++++++++++++++++++++++++++++++++++++++++
 builtin/replay.c               | 380 ++++----------------------------------
 command-list.txt               |   1 +
 git.c                          |   1 +
 meson.build                    |   2 +
 replay.c                       | 355 ++++++++++++++++++++++++++++++++++++
 replay.h                       |  80 ++++++++
 t/meson.build                  |   2 +
 t/t3450-history.sh             |  17 ++
 t/t3451-history-reword.sh      | 344 +++++++++++++++++++++++++++++++++++
 wt-status.c                    |  24 +++
 wt-status.h                    |   9 +
 17 files changed, 1352 insertions(+), 345 deletions(-)

Range-diff versus v8:

1: 4b58ceb517 ! 1: 5f3123028a builtin/replay: extract core logic to replay revisions

    @@ builtin/replay.c: static enum ref_action_mode get_ref_action_mode(struct reposit
     +	int contained;
     +};
     +
    -+struct replay_ref_updates {
    ++struct replay_result {
     +	struct replay_ref_update {
     +		char *refname;
     +		struct object_id old_oid;
     +		struct object_id new_oid;
    -+	} *items;
    -+	size_t nr, alloc;
    ++	} *updates;
    ++	size_t updates_nr, updates_alloc;
    ++
    ++	bool merge_conflict;
     +};
     +
    -+static void replay_ref_updates_release(struct replay_ref_updates *updates)
    ++static void replay_result_release(struct replay_result *result)
    ++{
    ++	for (size_t i = 0; i < result->updates_nr; i++)
    ++		free(result->updates[i].refname);
    ++	free(result->updates);
    ++}
    ++
    ++static void replay_result_queue_update(struct replay_result *result,
    ++				       const char *refname,
    ++				       const struct object_id *old_oid,
    ++				       const struct object_id *new_oid)
     +{
    -+	for (size_t i = 0; i < updates->nr; i++)
    -+		free(updates->items[i].refname);
    -+	free(updates->items);
    ++	ALLOC_GROW(result->updates, result->updates_nr + 1, result->updates_alloc);
    ++	result->updates[result->updates_nr].refname = xstrdup(refname);
    ++	result->updates[result->updates_nr].old_oid = *old_oid;
    ++	result->updates[result->updates_nr].new_oid = *new_oid;
    ++	result->updates_nr++;
     +}
     +
     +static int replay_revisions(struct repository *repo, struct rev_info *revs,
     +			    struct replay_revisions_options *opts,
    -+			    struct replay_ref_updates *updates)
    ++			    struct replay_result *out)
     +{
     +	kh_oid_map_t *replayed_commits = NULL;
     +	struct strset *update_refs = NULL;
    @@ builtin/replay.c: static enum ref_action_mode get_ref_action_mode(struct reposit
     +			if (decoration->type == DECORATION_REF_LOCAL &&
     +			    (opts->contained || strset_contains(update_refs,
     +								decoration->name))) {
    -+				ALLOC_GROW(updates->items, updates->nr + 1, updates->alloc);
    -+				updates->items[updates->nr].refname = xstrdup(decoration->name);
    -+				updates->items[updates->nr].old_oid = commit->object.oid;
    -+				updates->items[updates->nr].new_oid = last_commit->object.oid;
    -+				updates->nr++;
    ++				replay_result_queue_update(out, decoration->name,
    ++							   &commit->object.oid,
    ++							   &last_commit->object.oid);
     +			}
     +			decoration = decoration->next;
     +		}
     +	}
     +
     +	if (!result.clean) {
    ++		out->merge_conflict = true;
     +		ret = -1;
     +		goto out;
     +	}
     +
     +	/* In --advance mode, advance the target ref */
    -+	if (advance) {
    -+		ALLOC_GROW(updates->items, updates->nr + 1, updates->alloc);
    -+		updates->items[updates->nr].refname = xstrdup(advance);
    -+		updates->items[updates->nr].old_oid = onto->object.oid;
    -+		updates->items[updates->nr].new_oid = last_commit->object.oid;
    -+		updates->nr++;
    -+	}
    ++	if (advance)
    ++		replay_result_queue_update(out, advance,
    ++					   &onto->object.oid,
    ++					   &last_commit->object.oid);
     +
     +	ret = 0;
     +
    @@ builtin/replay.c: int cmd_replay(int argc,
     -	const char *onto_name = NULL;
     -	int contained = 0;
     +	struct replay_revisions_options opts = { 0 };
    -+	struct replay_ref_updates updates = { 0 };
    ++	struct replay_result result = { 0 };
      	const char *ref_action = NULL;
      	enum ref_action_mode ref_mode;
     -
    @@ builtin/replay.c: int cmd_replay(int argc,
     -			   &onto, &update_refs);
     -
     -	/* FIXME: Should allow replaying commits with the first as a root commit */
    -+	ret = replay_revisions(repo, &revs, &opts, &updates);
    ++	ret = replay_revisions(repo, &revs, &opts, &result);
     +	if (ret)
     +		goto cleanup;
      
    @@ builtin/replay.c: int cmd_replay(int argc,
     -				      &onto->object.oid,
     -				      reflog_msg.buf,
     -				      &transaction_err) < 0) {
    -+	for (size_t i = 0; i < updates.nr; i++) {
    -+		ret = handle_ref_update(ref_mode, transaction, updates.items[i].refname,
    -+					&updates.items[i].new_oid, &updates.items[i].old_oid,
    ++	for (size_t i = 0; i < result.updates_nr; i++) {
    ++		ret = handle_ref_update(ref_mode, transaction, result.updates[i].refname,
    ++					&result.updates[i].new_oid, &result.updates[i].old_oid,
     +					reflog_msg.buf, &transaction_err);
     +		if (ret) {
      			ret = error(_("failed to update ref '%s': %s"),
     -				    advance_name, transaction_err.buf);
    -+				    updates.items[i].refname, transaction_err.buf);
    ++				    result.updates[i].refname, transaction_err.buf);
      			goto cleanup;
      		}
      	}
    @@ builtin/replay.c: int cmd_replay(int argc,
      cleanup:
      	if (transaction)
      		ref_transaction_free(transaction);
    -+	replay_ref_updates_release(&updates);
    ++	replay_result_release(&result);
      	strbuf_release(&transaction_err);
      	strbuf_release(&reflog_msg);
      	release_revisions(&revs);
    @@ builtin/replay.c: int cmd_replay(int argc,
     -	if (ret < 0)
     -		exit(128);
     -	return ret ? 0 : 1;
    -+	return ret ? 1 : 0;
    ++	if (ret) {
    ++		if (result.merge_conflict)
    ++			return 1;
    ++		return 128;
    ++	}
    ++
    ++	return 0;
      }
2:  2b46a91628 ! 2:  fd63cca82f builtin/replay: move core logic into "libgit.a"
    @@ builtin/replay.c: static enum ref_action_mode get_ref_action_mode(struct reposit
     -	int contained;
     -};
     -
    --struct replay_ref_updates {
    +-struct replay_result {
     -	struct replay_ref_update {
     -		char *refname;
     -		struct object_id old_oid;
     -		struct object_id new_oid;
    --	} *items;
    --	size_t nr, alloc;
    +-	} *updates;
    +-	size_t updates_nr, updates_alloc;
    +-
    +-	bool merge_conflict;
     -};
     -
    --static void replay_ref_updates_release(struct replay_ref_updates *updates)
    +-static void replay_result_release(struct replay_result *result)
     -{
    --	for (size_t i = 0; i < updates->nr; i++)
    --		free(updates->items[i].refname);
    --	free(updates->items);
    +-	for (size_t i = 0; i < result->updates_nr; i++)
    +-		free(result->updates[i].refname);
    +-	free(result->updates);
    +-}
    +-
    +-static void replay_result_queue_update(struct replay_result *result,
    +-				       const char *refname,
    +-				       const struct object_id *old_oid,
    +-				       const struct object_id *new_oid)
    +-{
    +-	ALLOC_GROW(result->updates, result->updates_nr + 1, result->updates_alloc);
    +-	result->updates[result->updates_nr].refname = xstrdup(refname);
    +-	result->updates[result->updates_nr].old_oid = *old_oid;
    +-	result->updates[result->updates_nr].new_oid = *new_oid;
    +-	result->updates_nr++;
     -}
     -
     -static int replay_revisions(struct repository *repo, struct rev_info *revs,
     -			    struct replay_revisions_options *opts,
    --			    struct replay_ref_updates *updates)
    +-			    struct replay_result *out)
     -{
     -	kh_oid_map_t *replayed_commits = NULL;
     -	struct strset *update_refs = NULL;
    @@ builtin/replay.c: static enum ref_action_mode get_ref_action_mode(struct reposit
     -			if (decoration->type == DECORATION_REF_LOCAL &&
     -			    (opts->contained || strset_contains(update_refs,
     -								decoration->name))) {
    --				ALLOC_GROW(updates->items, updates->nr + 1, updates->alloc);
    --				updates->items[updates->nr].refname = xstrdup(decoration->name);
    --				updates->items[updates->nr].old_oid = commit->object.oid;
    --				updates->items[updates->nr].new_oid = last_commit->object.oid;
    --				updates->nr++;
    +-				replay_result_queue_update(out, decoration->name,
    +-							   &commit->object.oid,
    +-							   &last_commit->object.oid);
     -			}
     -			decoration = decoration->next;
     -		}
     -	}
     -
     -	if (!result.clean) {
    +-		out->merge_conflict = true;
     -		ret = -1;
     -		goto out;
     -	}
     -
     -	/* In --advance mode, advance the target ref */
    --	if (advance) {
    --		ALLOC_GROW(updates->items, updates->nr + 1, updates->alloc);
    --		updates->items[updates->nr].refname = xstrdup(advance);
    --		updates->items[updates->nr].old_oid = onto->object.oid;
    --		updates->items[updates->nr].new_oid = last_commit->object.oid;
    --		updates->nr++;
    --	}
    +-	if (advance)
    +-		replay_result_queue_update(out, advance,
    +-					   &onto->object.oid,
    +-					   &last_commit->object.oid);
     -
     -	ret = 0;
     -
    @@ replay.c (new)
     +	return create_commit(repo, result->tree, pickme, replayed_base);
     +}
     +
    -+void replay_ref_updates_release(struct replay_ref_updates *updates)
    ++void replay_result_release(struct replay_result *result)
     +{
    -+	for (size_t i = 0; i < updates->nr; i++)
    -+		free(updates->items[i].refname);
    -+	free(updates->items);
    ++	for (size_t i = 0; i < result->updates_nr; i++)
    ++		free(result->updates[i].refname);
    ++	free(result->updates);
    ++}
    ++
    ++static void replay_result_queue_update(struct replay_result *result,
    ++				       const char *refname,
    ++				       const struct object_id *old_oid,
    ++				       const struct object_id *new_oid)
    ++{
    ++	ALLOC_GROW(result->updates, result->updates_nr + 1, result->updates_alloc);
    ++	result->updates[result->updates_nr].refname = xstrdup(refname);
    ++	result->updates[result->updates_nr].old_oid = *old_oid;
    ++	result->updates[result->updates_nr].new_oid = *new_oid;
    ++	result->updates_nr++;
     +}
     +
     +int replay_revisions(struct repository *repo, struct rev_info *revs,
     +		     struct replay_revisions_options *opts,
    -+		     struct replay_ref_updates *updates)
    ++		     struct replay_result *out)
     +{
     +	kh_oid_map_t *replayed_commits = NULL;
     +	struct strset *update_refs = NULL;
    @@ replay.c (new)
     +			if (decoration->type == DECORATION_REF_LOCAL &&
     +			    (opts->contained || strset_contains(update_refs,
     +								decoration->name))) {
    -+				ALLOC_GROW(updates->items, updates->nr + 1, updates->alloc);
    -+				updates->items[updates->nr].refname = xstrdup(decoration->name);
    -+				updates->items[updates->nr].old_oid = commit->object.oid;
    -+				updates->items[updates->nr].new_oid = last_commit->object.oid;
    -+				updates->nr++;
    ++				replay_result_queue_update(out, decoration->name,
    ++							   &commit->object.oid,
    ++							   &last_commit->object.oid);
     +			}
     +			decoration = decoration->next;
     +		}
     +	}
     +
     +	if (!result.clean) {
    ++		out->merge_conflict = true;
     +		ret = -1;
     +		goto out;
     +	}
     +
     +	/* In --advance mode, advance the target ref */
    -+	if (advance) {
    -+		ALLOC_GROW(updates->items, updates->nr + 1, updates->alloc);
    -+		updates->items[updates->nr].refname = xstrdup(advance);
    -+		updates->items[updates->nr].old_oid = onto->object.oid;
    -+		updates->items[updates->nr].new_oid = last_commit->object.oid;
    -+		updates->nr++;
    -+	}
    ++	if (advance)
    ++		replay_result_queue_update(out, advance,
    ++					   &onto->object.oid,
    ++					   &last_commit->object.oid);
     +
     +	ret = 0;
     +
    @@ replay.h (new)
     +};
     +
     +/* This struct is used as an out-parameter by `replay_revisions()`. */
    -+struct replay_ref_updates {
    ++struct replay_result {
     +	/*
     +	 * The set of reference updates that are caused by replaying the
     +	 * commits.
    @@ replay.h (new)
     +		char *refname;
     +		struct object_id old_oid;
     +		struct object_id new_oid;
    -+	} *items;
    -+	size_t nr, alloc;
    ++	} *updates;
    ++	size_t updates_nr, updates_alloc;
    ++
    ++	/* Set to true in case the replay failed with a merge conflict. */
    ++	bool merge_conflict;
     +};
     +
    -+void replay_ref_updates_release(struct replay_ref_updates *updates);
    ++void replay_result_release(struct replay_result *result);
     +
     +/*
     + * Replay a set of commits onto a new location. Leaves both the working tree,
    @@ replay.h (new)
     + */
     +int replay_revisions(struct repository *repo, struct rev_info *revs,
     +		     struct replay_revisions_options *opts,
    -+		     struct replay_ref_updates *updates);
    ++		     struct replay_result *out);
     +
     +#endif
3:  881988bcfa = 3:  eb455cade1 replay: small set of cleanups
4:  197fa292c4 ! 4:  ccd323f6db replay: yield the object ID of the final rewritten commit

@@ Commit message

## replay.c ##
@@ replay.c: int replay_revisions(struct repository *repo, struct rev_info *revs,
- updates->nr++;
- }
+ &onto->object.oid,
+ &last_commit->object.oid);

-+ updates->final_oid = last_commit->object.oid;
++ out->final_oid = last_commit->object.oid;
+
ret = 0;

out:

## replay.h ##
-@@ replay.h: struct replay_ref_updates {
- struct object_id new_oid;
- } *items;
- size_t nr, alloc;
+@@ replay.h: struct replay_result {
+
+ /* Set to true in case the replay failed with a merge conflict. */
+ bool merge_conflict;
+
+ /*
+ * The final object ID that was rewritten. Note that this field has
@@ replay.h: struct replay_ref_updates {
+ struct object_id final_oid;
};

- void replay_ref_updates_release(struct replay_ref_updates *updates);
+ void replay_result_release(struct replay_result *result);

5:  91df8f3813 = 5:  a40034bcc1 wt-status: provide function to expose status for trees
6:  025e13874e ! 6:  4d566d6c43 builtin: add new "history" command

@@ Commit message
splitting up a commit into two are way more involved than that and require a whole series of commands.

- Another problem that rebases have is that dependent branches are not
- being updated. The use of stacked branches has grown quite common with
- competiting version control systems like Jujutsu though, so it clearly
- is a need that users have. While rebases _can_ serve this use case if
- one always works on the latest stacked branch, it is somewhat awkward
- and very easy to get wrong.
+ Rebases also do not update dependent branches. The use of stacked
+ branches has grown quite common with competing version control systems
+ like Jujutsu though, so it clearly is a need that users have. While
+ rebases _can_ serve this use case if one always works on the latest
+ stacked branch, it is somewhat awkward and very easy to get wrong.

Add a new "history" command to plug these gaps. This command will have several different subcommands to imperatively rewrite history for common
7: b5cfe7da4e ! 7: 666fec826c builtin/history: implement "reword" subcommand

    @@ builtin/history.c
     +{
     +	const struct name_decoration *decoration;
     +	struct replay_revisions_options opts = { 0 };
    -+	struct replay_ref_updates updates = {
    ++	struct replay_result result = {
     +		.final_oid = rewritten->object.oid,
     +	};
     +	struct ref_transaction *transaction = NULL;
    @@ builtin/history.c
     +
     +	opts.onto = oid_to_hex_r(hex, &rewritten->object.oid);
     +
    -+	ret = replay_revisions(repo, &revs, &opts, &updates);
    ++	ret = replay_revisions(repo, &revs, &opts, &result);
     +	if (ret)
     +		goto out;
     +
    @@ builtin/history.c
     +			goto out;
     +		}
     +
    -+		for (size_t i = 0; i < updates.nr; i++) {
    ++		for (size_t i = 0; i < result.updates_nr; i++) {
     +			ret = ref_transaction_update(transaction,
    -+						     updates.items[i].refname,
    -+						     &updates.items[i].new_oid,
    -+						     &updates.items[i].old_oid,
    ++						     result.updates[i].refname,
    ++						     &result.updates[i].new_oid,
    ++						     &result.updates[i].old_oid,
     +						     NULL, NULL, 0, reflog_msg, &err);
     +			if (ret) {
     +				ret = error(_("failed to update ref '%s': %s"),
    -+					    updates.items[i].refname, err.buf);
    ++					    result.updates[i].refname, err.buf);
     +				goto out;
     +			}
     +		}
    @@ builtin/history.c
     +		break;
     +	case REF_ACTION_HEAD:
     +		ret = refs_update_ref(get_main_ref_store(repo), reflog_msg, "HEAD",
    -+				      &updates.final_oid, &head->object.oid, 0,
    ++				      &result.final_oid, &head->object.oid, 0,
     +				      UPDATE_REFS_MSG_ON_ERR);
     +		if (ret)
     +			goto out;
     +		break;
     +	case REF_ACTION_PRINT:
    -+		for (size_t i = 0; i < updates.nr; i++)
    ++		for (size_t i = 0; i < result.updates_nr; i++)
     +			printf("update %s %s %s\n",
    -+			       updates.items[i].refname,
    -+			       oid_to_hex(&updates.items[i].new_oid),
    -+			       oid_to_hex(&updates.items[i].old_oid));
    ++			       result.updates[i].refname,
    ++			       oid_to_hex(&result.updates[i].new_oid),
    ++			       oid_to_hex(&result.updates[i].old_oid));
     +		break;
     +	default:
     +		BUG("unsupported ref action %d", action);
    @@ builtin/history.c
     +	ret = 0;
     +
     +out:
    -+	replay_ref_updates_release(&updates);
     +	ref_transaction_free(transaction);
    ++	replay_result_release(&result);
     +	release_revisions(&revs);
     +	strbuf_release(&err);
     +	strvec_clear(&args);

---
base-commit: 02bdc12118c43e0a65258eb742492965859bffb6
change-id: 20250819-b4-pks-history-builtin-83398f9a05f0

#300 lore raw

PATCH v9 1/7 builtin/replay: extract core logic to replay revisions

We're about to move the core logic used to replay revisions onto a new base into the "libgit.a" library. Prepare for this by pulling out the logic into a new function replay_revisions() that:

1. Takes a set of revisions to replay and some options that tell it how it ought to replay the revisions.

2. Replays the commits.

3. Records any reference updates that would be caused by replaying the commits in a structure that is owned by the caller.

The logic itself will be moved into a separate file in the next commit. This change is not expected to cause user-visible change in behaviour.

---
 builtin/replay.c | 274 +++++++++++++++++++++++++++++++++----------------------
 1 file changed, 165 insertions(+), 109 deletions(-)
builtin/replay.c +165 -109
index 1960bbbee8..df3b32a52d 100644
@@ -278,6 +278,137 @@ static enum ref_action_mode get_ref_action_mode(struct repository *repo, const c
 	return REF_ACTION_UPDATE;
 }
 
+struct replay_revisions_options {
+	const char *advance;
+	const char *onto;
+	int contained;
+};
+
+struct replay_result {
+	struct replay_ref_update {
+		char *refname;
+		struct object_id old_oid;
+		struct object_id new_oid;
+	} *updates;
+	size_t updates_nr, updates_alloc;
+
+	bool merge_conflict;
+};
+
+static void replay_result_release(struct replay_result *result)
+{
+	for (size_t i = 0; i < result->updates_nr; i++)
+		free(result->updates[i].refname);
+	free(result->updates);
+}
+
+static void replay_result_queue_update(struct replay_result *result,
+				       const char *refname,
+				       const struct object_id *old_oid,
+				       const struct object_id *new_oid)
+{
+	ALLOC_GROW(result->updates, result->updates_nr + 1, result->updates_alloc);
+	result->updates[result->updates_nr].refname = xstrdup(refname);
+	result->updates[result->updates_nr].old_oid = *old_oid;
+	result->updates[result->updates_nr].new_oid = *new_oid;
+	result->updates_nr++;
+}
+
+static int replay_revisions(struct repository *repo, struct rev_info *revs,
+			    struct replay_revisions_options *opts,
+			    struct replay_result *out)
+{
+	kh_oid_map_t *replayed_commits = NULL;
+	struct strset *update_refs = NULL;
+	struct commit *last_commit = NULL;
+	struct commit *commit;
+	struct commit *onto = NULL;
+	struct merge_options merge_opt;
+	struct merge_result result;
+	char *advance;
+	int ret;
+
+	advance = xstrdup_or_null(opts->advance);
+	set_up_replay_mode(repo, &revs->cmdline, opts->onto, &advance,
+			   &onto, &update_refs);
+
+	/* FIXME: Should allow replaying commits with the first as a root commit */
+
+	if (prepare_revision_walk(revs) < 0) {
+		ret = error(_("error preparing revisions"));
+		goto out;
+	}
+
+	init_basic_merge_options(&merge_opt, repo);
+	memset(&result, 0, sizeof(result));
+	merge_opt.show_rename_progress = 0;
+	last_commit = onto;
+	replayed_commits = kh_init_oid_map();
+	while ((commit = get_revision(revs))) {
+		const struct name_decoration *decoration;
+		khint_t pos;
+		int hr;
+
+		if (!commit->parents)
+			die(_("replaying down from root commit is not supported yet!"));
+		if (commit->parents->next)
+			die(_("replaying merge commits is not supported yet!"));
+
+		last_commit = pick_regular_commit(repo, commit, replayed_commits,
+						  onto, &merge_opt, &result);
+		if (!last_commit)
+			break;
+
+		/* Record commit -> last_commit mapping */
+		pos = kh_put_oid_map(replayed_commits, commit->object.oid, &hr);
+		if (hr == 0)
+			BUG("Duplicate rewritten commit: %s\n",
+			    oid_to_hex(&commit->object.oid));
+		kh_value(replayed_commits, pos) = last_commit;
+
+		/* Update any necessary branches */
+		if (advance)
+			continue;
+		decoration = get_name_decoration(&commit->object);
+		if (!decoration)
+			continue;
+		while (decoration) {
+			if (decoration->type == DECORATION_REF_LOCAL &&
+			    (opts->contained || strset_contains(update_refs,
+								decoration->name))) {
+				replay_result_queue_update(out, decoration->name,
+							   &commit->object.oid,
+							   &last_commit->object.oid);
+			}
+			decoration = decoration->next;
+		}
+	}
+
+	if (!result.clean) {
+		out->merge_conflict = true;
+		ret = -1;
+		goto out;
+	}
+
+	/* In --advance mode, advance the target ref */
+	if (advance)
+		replay_result_queue_update(out, advance,
+					   &onto->object.oid,
+					   &last_commit->object.oid);
+
+	ret = 0;
+
+out:
+	if (update_refs) {
+		strset_clear(update_refs);
+		free(update_refs);
+	}
+	kh_destroy_oid_map(replayed_commits);
+	merge_finalize(&merge_opt, &result);
+	free(advance);
+	return ret;
+}
+
 static int handle_ref_update(enum ref_action_mode mode,
 			     struct ref_transaction *transaction,
 			     const char *refname,
@@ -306,21 +437,11 @@ int cmd_replay(int argc,
 	       const char *prefix,
 	       struct repository *repo)
 {
-	const char *advance_name_opt = NULL;
-	char *advance_name = NULL;
-	struct commit *onto = NULL;
-	const char *onto_name = NULL;
-	int contained = 0;
+	struct replay_revisions_options opts = { 0 };
+	struct replay_result result = { 0 };
 	const char *ref_action = NULL;
 	enum ref_action_mode ref_mode;
-
 	struct rev_info revs;
-	struct commit *last_commit = NULL;
-	struct commit *commit;
-	struct merge_options merge_opt;
-	struct merge_result result;
-	struct strset *update_refs = NULL;
-	kh_oid_map_t *replayed_commits;
 	struct ref_transaction *transaction = NULL;
 	struct strbuf transaction_err = STRBUF_INIT;
 	struct strbuf reflog_msg = STRBUF_INIT;
@@ -333,13 +454,13 @@ int cmd_replay(int argc,
 		NULL
 	};
 	struct option replay_options[] = {
-		OPT_STRING(0, "advance", &advance_name_opt,
+		OPT_STRING(0, "advance", &opts.advance,
 			   N_("branch"),
 			   N_("make replay advance given branch")),
-		OPT_STRING(0, "onto", &onto_name,
+		OPT_STRING(0, "onto", &opts.onto,
 			   N_("revision"),
 			   N_("replay onto given commit")),
-		OPT_BOOL(0, "contained", &contained,
+		OPT_BOOL(0, "contained", &opts.contained,
 			 N_("update all branches that point at commits in <revision-range>")),
 		OPT_STRING(0, "ref-action", &ref_action,
 			   N_("mode"),
@@ -350,19 +471,17 @@ int cmd_replay(int argc,
 	argc = parse_options(argc, argv, prefix, replay_options, replay_usage,
 			     PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN_OPT);
 
-	if (!onto_name && !advance_name_opt) {
+	if (!opts.onto && !opts.advance) {
 		error(_("option --onto or --advance is mandatory"));
 		usage_with_options(replay_usage, replay_options);
 	}
 
-	die_for_incompatible_opt2(!!advance_name_opt, "--advance",
-				  contained, "--contained");
+	die_for_incompatible_opt2(!!opts.advance, "--advance",
+				  opts.contained, "--contained");
 
 	/* Parse ref action mode from command line or config */
 	ref_mode = get_ref_action_mode(repo, ref_action);
 
-	advance_name = xstrdup_or_null(advance_name_opt);
-
 	repo_init_revisions(repo, &revs, prefix);
 
 	/*
@@ -414,18 +533,19 @@ int cmd_replay(int argc,
 		revs.simplify_history = 0;
 	}
 
-	set_up_replay_mode(repo, &revs.cmdline,
-			   onto_name, &advance_name,
-			   &onto, &update_refs);
-
-	/* FIXME: Should allow replaying commits with the first as a root commit */
+	ret = replay_revisions(repo, &revs, &opts, &result);
+	if (ret)
+		goto cleanup;
 
 	/* Build reflog message */
-	if (advance_name_opt)
-		strbuf_addf(&reflog_msg, "replay --advance %s", advance_name_opt);
-	else
-		strbuf_addf(&reflog_msg, "replay --onto %s",
-			    oid_to_hex(&onto->object.oid));
+	if (opts.advance) {
+		strbuf_addf(&reflog_msg, "replay --advance %s", opts.advance);
+	} else {
+		struct object_id oid;
+		if (repo_get_oid_committish(repo, opts.onto, &oid))
+			BUG("--onto commit should have been resolved beforehand already");
+		strbuf_addf(&reflog_msg, "replay --onto %s", oid_to_hex(&oid));
+	}
 
 	/* Initialize ref transaction if using update mode */
 	if (ref_mode == REF_ACTION_UPDATE) {
@@ -438,78 +558,19 @@ int cmd_replay(int argc,
 		}
 	}
 
-	if (prepare_revision_walk(&revs) < 0) {
-		ret = error(_("error preparing revisions"));
-		goto cleanup;
-	}
-
-	init_basic_merge_options(&merge_opt, repo);
-	memset(&result, 0, sizeof(result));
-	merge_opt.show_rename_progress = 0;
-	last_commit = onto;
-	replayed_commits = kh_init_oid_map();
-	while ((commit = get_revision(&revs))) {
-		const struct name_decoration *decoration;
-		khint_t pos;
-		int hr;
-
-		if (!commit->parents)
-			die(_("replaying down from root commit is not supported yet!"));
-		if (commit->parents->next)
-			die(_("replaying merge commits is not supported yet!"));
-
-		last_commit = pick_regular_commit(repo, commit, replayed_commits,
-						  onto, &merge_opt, &result);
-		if (!last_commit)
-			break;
-
-		/* Record commit -> last_commit mapping */
-		pos = kh_put_oid_map(replayed_commits, commit->object.oid, &hr);
-		if (hr == 0)
-			BUG("Duplicate rewritten commit: %s\n",
-			    oid_to_hex(&commit->object.oid));
-		kh_value(replayed_commits, pos) = last_commit;
-
-		/* Update any necessary branches */
-		if (advance_name)
-			continue;
-		decoration = get_name_decoration(&commit->object);
-		if (!decoration)
-			continue;
-		while (decoration) {
-			if (decoration->type == DECORATION_REF_LOCAL &&
-			    (contained || strset_contains(update_refs,
-							  decoration->name))) {
-				if (handle_ref_update(ref_mode, transaction,
-						      decoration->name,
-						      &last_commit->object.oid,
-						      &commit->object.oid,
-						      reflog_msg.buf,
-						      &transaction_err) < 0) {
-					ret = error(_("failed to update ref '%s': %s"),
-						    decoration->name, transaction_err.buf);
-					goto cleanup;
-				}
-			}
-			decoration = decoration->next;
-		}
-	}
-
-	/* In --advance mode, advance the target ref */
-	if (result.clean == 1 && advance_name) {
-		if (handle_ref_update(ref_mode, transaction, advance_name,
-				      &last_commit->object.oid,
-				      &onto->object.oid,
-				      reflog_msg.buf,
-				      &transaction_err) < 0) {
+	for (size_t i = 0; i < result.updates_nr; i++) {
+		ret = handle_ref_update(ref_mode, transaction, result.updates[i].refname,
+					&result.updates[i].new_oid, &result.updates[i].old_oid,
+					reflog_msg.buf, &transaction_err);
+		if (ret) {
 			ret = error(_("failed to update ref '%s': %s"),
-				    advance_name, transaction_err.buf);
+				    result.updates[i].refname, transaction_err.buf);
 			goto cleanup;
 		}
 	}
 
 	/* Commit the ref transaction if we have one */
-	if (transaction && result.clean == 1) {
+	if (transaction) {
 		if (ref_transaction_commit(transaction, &transaction_err)) {
 			ret = error(_("failed to commit ref transaction: %s"),
 				    transaction_err.buf);
@@ -517,24 +578,19 @@ int cmd_replay(int argc,
 		}
 	}
 
-	merge_finalize(&merge_opt, &result);
-	kh_destroy_oid_map(replayed_commits);
-	if (update_refs) {
-		strset_clear(update_refs);
-		free(update_refs);
-	}
-	ret = result.clean;
-
 cleanup:
 	if (transaction)
 		ref_transaction_free(transaction);
+	replay_result_release(&result);
 	strbuf_release(&transaction_err);
 	strbuf_release(&reflog_msg);
 	release_revisions(&revs);
-	free(advance_name);
 
-	/* Return */
-	if (ret < 0)
-		exit(128);
-	return ret ? 0 : 1;
+	if (ret) {
+		if (result.merge_conflict)
+			return 1;
+		return 128;
+	}
+
+	return 0;
 }
Signature · 1 line
2.52.0.542.g9473a8513b.dirty
#301 lore raw

Re: [PATCH v9 1/7] builtin/replay: extract core logic to replay revisions

Quoted 58 lines · Patrick Steinhardt

We're about to move the core logic used to replay revisions onto a new base into the "libgit.a" library. Prepare for this by pulling out the logic into a new function replay_revisions() that:

1. Takes a set of revisions to replay and some options that tell it how it ought to replay the revisions.

2. Replays the commits.

3. Records any reference updates that would be caused by replaying the commits in a structure that is owned by the caller.

The logic itself will be moved into a separate file in the next commit. This change is not expected to cause user-visible change in behaviour.

---
 builtin/replay.c | 274 +++++++++++++++++++++++++++++++++----------------------
 1 file changed, 165 insertions(+), 109 deletions(-)
builtin/replay.c +29 -0
index 1960bbbee8..df3b32a52d 100644
@@ -278,6 +278,137 @@ static enum ref_action_mode get_ref_action_mode(struct repository *repo, const c
        return REF_ACTION_UPDATE;
 }
 
+struct replay_revisions_options {
+       const char *advance;
+       const char *onto;
+       int contained;
+};
+
+struct replay_result {
+       struct replay_ref_update {
+               char *refname;
+               struct object_id old_oid;
+               struct object_id new_oid;
+       } *updates;
+       size_t updates_nr, updates_alloc;
+
+       bool merge_conflict;
+};
+
+static void replay_result_release(struct replay_result *result)
+{
+       for (size_t i = 0; i < result->updates_nr; i++)
+               free(result->updates[i].refname);
+       free(result->updates);
+}
+
+static void replay_result_queue_update(struct replay_result *result,
+                                      const char *refname,
+                                      const struct object_id *old_oid,
+                                      const struct object_id *new_oid)
+{

builtin/replay.c static enum ref_action_mode get_ref_action_mode(struct repository *repo, const c · line 319

Quoted 10 lines
builtin/replay.c +10 -0
+       ALLOC_GROW(result->updates, result->updates_nr + 1, result->updates_alloc);
+       result->updates[result->updates_nr].refname = xstrdup(refname);
+       result->updates[result->updates_nr].old_oid = *old_oid;
+       result->updates[result->updates_nr].new_oid = *new_oid;
+       result->updates_nr++;
+}
+
+static int replay_revisions(struct repository *repo, struct rev_info *revs,
+                           struct replay_revisions_options *opts,
+                           struct replay_result *out)

Why have both repo & revs? Can't we get repo from revs->repo?

Quoted 61 lines
builtin/replay.c +61 -0
+{
+       kh_oid_map_t *replayed_commits = NULL;
+       struct strset *update_refs = NULL;
+       struct commit *last_commit = NULL;
+       struct commit *commit;
+       struct commit *onto = NULL;
+       struct merge_options merge_opt;
+       struct merge_result result;
+       char *advance;
+       int ret;
+
+       advance = xstrdup_or_null(opts->advance);
+       set_up_replay_mode(repo, &revs->cmdline, opts->onto, &advance,
+                          &onto, &update_refs);
+
+       /* FIXME: Should allow replaying commits with the first as a root commit */
+
+       if (prepare_revision_walk(revs) < 0) {
+               ret = error(_("error preparing revisions"));
+               goto out;
+       }
+
+       init_basic_merge_options(&merge_opt, repo);
+       memset(&result, 0, sizeof(result));
+       merge_opt.show_rename_progress = 0;
+       last_commit = onto;
+       replayed_commits = kh_init_oid_map();
+       while ((commit = get_revision(revs))) {
+               const struct name_decoration *decoration;
+               khint_t pos;
+               int hr;
+
+               if (!commit->parents)
+                       die(_("replaying down from root commit is not supported yet!"));
+               if (commit->parents->next)
+                       die(_("replaying merge commits is not supported yet!"));
+
+               last_commit = pick_regular_commit(repo, commit, replayed_commits,
+                                                 onto, &merge_opt, &result);
+               if (!last_commit)
+                       break;
+
+               /* Record commit -> last_commit mapping */
+               pos = kh_put_oid_map(replayed_commits, commit->object.oid, &hr);
+               if (hr == 0)
+                       BUG("Duplicate rewritten commit: %s\n",
+                           oid_to_hex(&commit->object.oid));
+               kh_value(replayed_commits, pos) = last_commit;
+
+               /* Update any necessary branches */
+               if (advance)
+                       continue;
+               decoration = get_name_decoration(&commit->object);
+               if (!decoration)
+                       continue;
+               while (decoration) {
+                       if (decoration->type == DECORATION_REF_LOCAL &&
+                           (opts->contained || strset_contains(update_refs,
+                                                               decoration->name))) {
+                               replay_result_queue_update(out, decoration->name,
+                                                          &commit->object.oid,

builtin/replay.c static enum ref_action_mode get_ref_action_mode(struct repository *repo, const c · line 390

Quoted 10 lines
builtin/replay.c +10 -0
+                                                          &last_commit->object.oid);
+                       }
+                       decoration = decoration->next;
+               }
+       }
+
+       if (!result.clean) {
+               out->merge_conflict = true;
+               ret = -1;
+               goto out;

What? In the replay code before this series:

        ret = result.clean;
        [...]
        /* Return */
        if (ret < 0)
                exit(128);
        return ret ? 0 : 1;

So, !result.clean should result in a return code of 1, not -1.

Quoted 222 lines
builtin/replay.c +48 -104
+       }
+
+       /* In --advance mode, advance the target ref */
+       if (advance)
+               replay_result_queue_update(out, advance,
+                                          &onto->object.oid,
+                                          &last_commit->object.oid);
+
+       ret = 0;
+
+out:
+       if (update_refs) {
+               strset_clear(update_refs);
+               free(update_refs);
+       }
+       kh_destroy_oid_map(replayed_commits);
+       merge_finalize(&merge_opt, &result);
+       free(advance);
+       return ret;
+}
+
 static int handle_ref_update(enum ref_action_mode mode,
                             struct ref_transaction *transaction,
                             const char *refname,
@@ -306,21 +437,11 @@ int cmd_replay(int argc,
               const char *prefix,
               struct repository *repo)
 {
-       const char *advance_name_opt = NULL;
-       char *advance_name = NULL;
-       struct commit *onto = NULL;
-       const char *onto_name = NULL;
-       int contained = 0;
+       struct replay_revisions_options opts = { 0 };
+       struct replay_result result = { 0 };
        const char *ref_action = NULL;
        enum ref_action_mode ref_mode;
-
        struct rev_info revs;
-       struct commit *last_commit = NULL;
-       struct commit *commit;
-       struct merge_options merge_opt;
-       struct merge_result result;
-       struct strset *update_refs = NULL;
-       kh_oid_map_t *replayed_commits;
        struct ref_transaction *transaction = NULL;
        struct strbuf transaction_err = STRBUF_INIT;
        struct strbuf reflog_msg = STRBUF_INIT;
@@ -333,13 +454,13 @@ int cmd_replay(int argc,
                NULL
        };
        struct option replay_options[] = {
-               OPT_STRING(0, "advance", &advance_name_opt,
+               OPT_STRING(0, "advance", &opts.advance,
                           N_("branch"),
                           N_("make replay advance given branch")),
-               OPT_STRING(0, "onto", &onto_name,
+               OPT_STRING(0, "onto", &opts.onto,
                           N_("revision"),
                           N_("replay onto given commit")),
-               OPT_BOOL(0, "contained", &contained,
+               OPT_BOOL(0, "contained", &opts.contained,
                         N_("update all branches that point at commits in <revision-range>")),
                OPT_STRING(0, "ref-action", &ref_action,
                           N_("mode"),
@@ -350,19 +471,17 @@ int cmd_replay(int argc,
        argc = parse_options(argc, argv, prefix, replay_options, replay_usage,
                             PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN_OPT);
 
-       if (!onto_name && !advance_name_opt) {
+       if (!opts.onto && !opts.advance) {
                error(_("option --onto or --advance is mandatory"));
                usage_with_options(replay_usage, replay_options);
        }
 
-       die_for_incompatible_opt2(!!advance_name_opt, "--advance",
-                                 contained, "--contained");
+       die_for_incompatible_opt2(!!opts.advance, "--advance",
+                                 opts.contained, "--contained");
 
        /* Parse ref action mode from command line or config */
        ref_mode = get_ref_action_mode(repo, ref_action);
 
-       advance_name = xstrdup_or_null(advance_name_opt);
-
        repo_init_revisions(repo, &revs, prefix);
 
        /*
@@ -414,18 +533,19 @@ int cmd_replay(int argc,
                revs.simplify_history = 0;
        }
 
-       set_up_replay_mode(repo, &revs.cmdline,
-                          onto_name, &advance_name,
-                          &onto, &update_refs);
-
-       /* FIXME: Should allow replaying commits with the first as a root commit */
+       ret = replay_revisions(repo, &revs, &opts, &result);
+       if (ret)
+               goto cleanup;
 
        /* Build reflog message */
-       if (advance_name_opt)
-               strbuf_addf(&reflog_msg, "replay --advance %s", advance_name_opt);
-       else
-               strbuf_addf(&reflog_msg, "replay --onto %s",
-                           oid_to_hex(&onto->object.oid));
+       if (opts.advance) {
+               strbuf_addf(&reflog_msg, "replay --advance %s", opts.advance);
+       } else {
+               struct object_id oid;
+               if (repo_get_oid_committish(repo, opts.onto, &oid))
+                       BUG("--onto commit should have been resolved beforehand already");
+               strbuf_addf(&reflog_msg, "replay --onto %s", oid_to_hex(&oid));
+       }
 
        /* Initialize ref transaction if using update mode */
        if (ref_mode == REF_ACTION_UPDATE) {
@@ -438,78 +558,19 @@ int cmd_replay(int argc,
                }
        }
 
-       if (prepare_revision_walk(&revs) < 0) {
-               ret = error(_("error preparing revisions"));
-               goto cleanup;
-       }
-
-       init_basic_merge_options(&merge_opt, repo);
-       memset(&result, 0, sizeof(result));
-       merge_opt.show_rename_progress = 0;
-       last_commit = onto;
-       replayed_commits = kh_init_oid_map();
-       while ((commit = get_revision(&revs))) {
-               const struct name_decoration *decoration;
-               khint_t pos;
-               int hr;
-
-               if (!commit->parents)
-                       die(_("replaying down from root commit is not supported yet!"));
-               if (commit->parents->next)
-                       die(_("replaying merge commits is not supported yet!"));
-
-               last_commit = pick_regular_commit(repo, commit, replayed_commits,
-                                                 onto, &merge_opt, &result);
-               if (!last_commit)
-                       break;
-
-               /* Record commit -> last_commit mapping */
-               pos = kh_put_oid_map(replayed_commits, commit->object.oid, &hr);
-               if (hr == 0)
-                       BUG("Duplicate rewritten commit: %s\n",
-                           oid_to_hex(&commit->object.oid));
-               kh_value(replayed_commits, pos) = last_commit;
-
-               /* Update any necessary branches */
-               if (advance_name)
-                       continue;
-               decoration = get_name_decoration(&commit->object);
-               if (!decoration)
-                       continue;
-               while (decoration) {
-                       if (decoration->type == DECORATION_REF_LOCAL &&
-                           (contained || strset_contains(update_refs,
-                                                         decoration->name))) {
-                               if (handle_ref_update(ref_mode, transaction,
-                                                     decoration->name,
-                                                     &last_commit->object.oid,
-                                                     &commit->object.oid,
-                                                     reflog_msg.buf,
-                                                     &transaction_err) < 0) {
-                                       ret = error(_("failed to update ref '%s': %s"),
-                                                   decoration->name, transaction_err.buf);
-                                       goto cleanup;
-                               }
-                       }
-                       decoration = decoration->next;
-               }
-       }
-
-       /* In --advance mode, advance the target ref */
-       if (result.clean == 1 && advance_name) {
-               if (handle_ref_update(ref_mode, transaction, advance_name,
-                                     &last_commit->object.oid,
-                                     &onto->object.oid,
-                                     reflog_msg.buf,
-                                     &transaction_err) < 0) {
+       for (size_t i = 0; i < result.updates_nr; i++) {
+               ret = handle_ref_update(ref_mode, transaction, result.updates[i].refname,
+                                       &result.updates[i].new_oid, &result.updates[i].old_oid,
+                                       reflog_msg.buf, &transaction_err);
+               if (ret) {
                        ret = error(_("failed to update ref '%s': %s"),
-                                   advance_name, transaction_err.buf);
+                                   result.updates[i].refname, transaction_err.buf);
                        goto cleanup;
                }
        }
 
        /* Commit the ref transaction if we have one */
-       if (transaction && result.clean == 1) {
+       if (transaction) {
                if (ref_transaction_commit(transaction, &transaction_err)) {
                        ret = error(_("failed to commit ref transaction: %s"),
                                    transaction_err.buf);
@@ -517,24 +578,19 @@ int cmd_replay(int argc,
                }
        }
 
-       merge_finalize(&merge_opt, &result);
-       kh_destroy_oid_map(replayed_commits);
-       if (update_refs) {
-               strset_clear(update_refs);
-               free(update_refs);
-       }
-       ret = result.clean;
-
 cleanup:
        if (transaction)
                ref_transaction_free(transaction);
+       replay_result_release(&result);
        strbuf_release(&transaction_err);
        strbuf_release(&reflog_msg);

builtin/replay.c int cmd_replay(int argc, · line 591

Quoted 10 lines
builtin/replay.c +3 -5
        release_revisions(&revs);
-       free(advance_name);
 
-       /* Return */
-       if (ret < 0)
-               exit(128);
-       return ret ? 0 : 1;
+       if (ret) {
+               if (result.merge_conflict)
+                       return 1;

This feels like a rather Rube-Goldberg way to get this. Above where I highlighted where you set ret to -1 incorrectly, can we just set it to 1 there and then lose all this special logic in favor of "return ret;" here? Or am I overlooking something?

Quoted 8 lines
builtin/replay.c +4 -1
+               return 128;
+       }
+
+       return 0;
 }
 
--

2.52.0.542.g9473a8513b.dirty

#302 lore raw

Re: [PATCH v9 1/7] builtin/replay: extract core logic to replay revisions

Quoted 42 lines · Elijah Newren
Quoted 41 lines · Patrick Steinhardt
builtin/replay.c +33 -0
index 1960bbbee8..df3b32a52d 100644
@@ -278,6 +278,137 @@ static enum ref_action_mode get_ref_action_mode(struct repository *repo, const c
        return REF_ACTION_UPDATE;
 }
 
+struct replay_revisions_options {
+       const char *advance;
+       const char *onto;
+       int contained;
+};
+
+struct replay_result {
+       struct replay_ref_update {
+               char *refname;
+               struct object_id old_oid;
+               struct object_id new_oid;
+       } *updates;
+       size_t updates_nr, updates_alloc;
+
+       bool merge_conflict;
+};
+
+static void replay_result_release(struct replay_result *result)
+{
+       for (size_t i = 0; i < result->updates_nr; i++)
+               free(result->updates[i].refname);
+       free(result->updates);
+}
+
+static void replay_result_queue_update(struct replay_result *result,
+                                      const char *refname,
+                                      const struct object_id *old_oid,
+                                      const struct object_id *new_oid)
+{
+       ALLOC_GROW(result->updates, result->updates_nr + 1, result->updates_alloc);
+       result->updates[result->updates_nr].refname = xstrdup(refname);
+       result->updates[result->updates_nr].old_oid = *old_oid;
+       result->updates[result->updates_nr].new_oid = *new_oid;
Quoted 8 lines

builtin/replay.c static enum ref_action_mode get_ref_action_mode(struct repository *repo, const c · line 319

Quoted 6 lines
builtin/replay.c +6 -0
+       result->updates_nr++;
+}
+
+static int replay_revisions(struct repository *repo, struct rev_info *revs,
+                           struct replay_revisions_options *opts,
+                           struct replay_result *out)

Why have both repo & revs? Can't we get repo from revs->repo?

True indeed, will change.

Quoted 21 lines
Quoted 21 lines
builtin/replay.c +1 -9
@@ -517,24 +578,19 @@ int cmd_replay(int argc,
                }
        }
 
-       merge_finalize(&merge_opt, &result);
-       kh_destroy_oid_map(replayed_commits);
-       if (update_refs) {
-               strset_clear(update_refs);
-               free(update_refs);
-       }
-       ret = result.clean;
-
 cleanup:
        if (transaction)
                ref_transaction_free(transaction);
+       replay_result_release(&result);
        strbuf_release(&transaction_err);
        strbuf_release(&reflog_msg);
        release_revisions(&revs);
-       free(advance_name);
 
Quoted 12 lines

builtin/replay.c int cmd_replay(int argc, · line 591

Quoted 7 lines
builtin/replay.c +3 -4
-       /* Return */
-       if (ret < 0)
-               exit(128);
-       return ret ? 0 : 1;
+       if (ret) {
+               if (result.merge_conflict)
+                       return 1;

This feels like a rather Rube-Goldberg way to get this. Above where I highlighted where you set ret to -1 incorrectly, can we just set it to 1 there and then lose all this special logic in favor of "return ret;" here? Or am I overlooking something?

You're not really overlooking anything, no. The reason I did it this way here is to make the logic more explicit -- a simple return value is very fragile, and I broke this in v8 of this patch series already.

Furthermore, this is preparing for us to move this code into a separate library. Not all callers may want to handle conflicts the exact same, so I think it's sensible to explicitly tell the caller about such error cases. One way to do this is to use e.g. an enum to surface the info, but that is somewhat limiting. We may for example tell the caller later on what the conflicting commit was, and that's becoming way easier by having the info in sturct replay_result.

Patrick

#303 lore raw

PATCH v9 2/7 builtin/replay: move core logic into "libgit.a"

In reply to Patrick Steinhardt

Move the core logic used to replay commits into "libgit.a" so that it can be easily reused by other commands. It will be used in a subsequent commit where we're about to introduce a new git-history(1) command.

Note that with this change we have no sign-comparison warnings anymore, and neither do we depend on the_repository.

---
 Makefile         |   1 +
 builtin/replay.c | 368 +------------------------------------------------------
 meson.build      |   1 +
 replay.c         | 355 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 replay.h         |  64 ++++++++++
 5 files changed, 422 insertions(+), 367 deletions(-)
Makefile +1 -0
index b7eba509c6..1c64a5d2ae 100644
@@ -1285,6 +1285,7 @@ LIB_OBJS += repack-geometry.o
 LIB_OBJS += repack-midx.o
 LIB_OBJS += repack-promisor.o
 LIB_OBJS += replace-object.o
+LIB_OBJS += replay.o
 LIB_OBJS += repo-settings.o
 LIB_OBJS += repository.o
 LIB_OBJS += rerere.o
builtin/replay.c +1 -367

395 lines not on this page · raw message

meson.build +1 -0
index dd52efd1c8..a5a4e99b25 100644
@@ -471,6 +471,7 @@ libgit_sources = [
   'repack-midx.c',
   'repack-promisor.c',
   'replace-object.c',
+  'replay.c',
   'repo-settings.c',
   'repository.c',
   'rerere.c',
replay.c new file +355 -0

355 lines not on this page · raw message

replay.h new file +64 -0

64 lines not on this page · raw message

Signature · 1 line
2.52.0.542.g9473a8513b.dirty
#304 lore raw

Re: [PATCH v9 2/7] builtin/replay: move core logic into "libgit.a"

Quoted 448 lines · Patrick Steinhardt

Move the core logic used to replay commits into "libgit.a" so that it can be easily reused by other commands. It will be used in a subsequent commit where we're about to introduce a new git-history(1) command.

Note that with this change we have no sign-comparison warnings anymore, and neither do we depend on the_repository.

---
 Makefile         |   1 +
 builtin/replay.c | 368 +------------------------------------------------------
 meson.build      |   1 +
 replay.c         | 355 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 replay.h         |  64 ++++++++++
 5 files changed, 422 insertions(+), 367 deletions(-)
Makefile +1 -0
index b7eba509c6..1c64a5d2ae 100644
@@ -1285,6 +1285,7 @@ LIB_OBJS += repack-geometry.o
 LIB_OBJS += repack-midx.o
 LIB_OBJS += repack-promisor.o
 LIB_OBJS += replace-object.o
+LIB_OBJS += replay.o
 LIB_OBJS += repo-settings.o
 LIB_OBJS += repository.o
 LIB_OBJS += rerere.o
builtin/replay.c +1 -367
index df3b32a52d..da8b7202f6 100644
@@ -2,257 +2,22 @@
  * "git replay" builtin command
  */
 
-#define USE_THE_REPOSITORY_VARIABLE
-#define DISABLE_SIGN_COMPARE_WARNINGS
-
 #include "git-compat-util.h"
 
 #include "builtin.h"
 #include "config.h"
-#include "environment.h"
 #include "hex.h"
-#include "lockfile.h"
-#include "merge-ort.h"
 #include "object-name.h"
 #include "parse-options.h"
 #include "refs.h"
+#include "replay.h"
 #include "revision.h"
-#include "strmap.h"
-#include <oidset.h>
-#include <tree.h>
 
 enum ref_action_mode {
        REF_ACTION_UPDATE,
        REF_ACTION_PRINT,
 };
 
-static const char *short_commit_name(struct repository *repo,
-                                    struct commit *commit)
-{
-       return repo_find_unique_abbrev(repo, &commit->object.oid,
-                                      DEFAULT_ABBREV);
-}
-
-static struct commit *peel_committish(struct repository *repo,
-                                     const char *name,
-                                     const char *mode)
-{
-       struct object *obj;
-       struct object_id oid;
-
-       if (repo_get_oid(repo, name, &oid))
-               die(_("'%s' is not a valid commit-ish for %s"), name, mode);
-       obj = parse_object_or_die(repo, &oid, name);
-       return (struct commit *)repo_peel_to_type(repo, name, 0, obj,
-                                                 OBJ_COMMIT);
-}
-
-static char *get_author(const char *message)
-{
-       size_t len;
-       const char *a;
-
-       a = find_commit_header(message, "author", &len);
-       if (a)
-               return xmemdupz(a, len);
-
-       return NULL;
-}
-
-static struct commit *create_commit(struct repository *repo,
-                                   struct tree *tree,
-                                   struct commit *based_on,
-                                   struct commit *parent)
-{
-       struct object_id ret;
-       struct object *obj = NULL;
-       struct commit_list *parents = NULL;
-       char *author;
-       char *sign_commit = NULL; /* FIXME: cli users might want to sign again */
-       struct commit_extra_header *extra = NULL;
-       struct strbuf msg = STRBUF_INIT;
-       const char *out_enc = get_commit_output_encoding();
-       const char *message = repo_logmsg_reencode(repo, based_on,
-                                                  NULL, out_enc);
-       const char *orig_message = NULL;
-       const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
-
-       commit_list_insert(parent, &parents);
-       extra = read_commit_extra_headers(based_on, exclude_gpgsig);
-       find_commit_subject(message, &orig_message);
-       strbuf_addstr(&msg, orig_message);
-       author = get_author(message);
-       reset_ident_date();
-       if (commit_tree_extended(msg.buf, msg.len, &tree->object.oid, parents,
-                                &ret, author, NULL, sign_commit, extra)) {
-               error(_("failed to write commit object"));
-               goto out;
-       }
-
-       obj = parse_object(repo, &ret);
-
-out:
-       repo_unuse_commit_buffer(the_repository, based_on, message);
-       free_commit_extra_headers(extra);
-       free_commit_list(parents);
-       strbuf_release(&msg);
-       free(author);
-       return (struct commit *)obj;
-}
-
-struct ref_info {
-       struct commit *onto;
-       struct strset positive_refs;
-       struct strset negative_refs;
-       int positive_refexprs;
-       int negative_refexprs;
-};
-
-static void get_ref_information(struct repository *repo,
-                               struct rev_cmdline_info *cmd_info,
-                               struct ref_info *ref_info)
-{
-       int i;
-
-       ref_info->onto = NULL;
-       strset_init(&ref_info->positive_refs);
-       strset_init(&ref_info->negative_refs);
-       ref_info->positive_refexprs = 0;
-       ref_info->negative_refexprs = 0;
-
-       /*
-        * When the user specifies e.g.
-        *   git replay origin/main..mybranch
-        *   git replay ^origin/next mybranch1 mybranch2
-        * we want to be able to determine where to replay the commits.  In
-        * these examples, the branches are probably based on an old version
-        * of either origin/main or origin/next, so we want to replay on the
-        * newest version of that branch.  In contrast we would want to error
-        * out if they ran
-        *   git replay ^origin/master ^origin/next mybranch
-        *   git replay mybranch~2..mybranch
-        * the first of those because there's no unique base to choose, and
-        * the second because they'd likely just be replaying commits on top
-        * of the same commit and not making any difference.
-        */
-       for (i = 0; i < cmd_info->nr; i++) {
-               struct rev_cmdline_entry *e = cmd_info->rev + i;
-               struct object_id oid;
-               const char *refexpr = e->name;
-               char *fullname = NULL;
-               int can_uniquely_dwim = 1;
-
-               if (*refexpr == '^')
-                       refexpr++;
-               if (repo_dwim_ref(repo, refexpr, strlen(refexpr), &oid, &fullname, 0) != 1)
-                       can_uniquely_dwim = 0;
-
-               if (e->flags & BOTTOM) {
-                       if (can_uniquely_dwim)
-                               strset_add(&ref_info->negative_refs, fullname);
-                       if (!ref_info->negative_refexprs)
-                               ref_info->onto = lookup_commit_reference_gently(repo,
-                                                                               &e->item->oid, 1);
-                       ref_info->negative_refexprs++;
-               } else {
-                       if (can_uniquely_dwim)
-                               strset_add(&ref_info->positive_refs, fullname);
-                       ref_info->positive_refexprs++;
-               }
-
-               free(fullname);
-       }
-}
-
-static void set_up_replay_mode(struct repository *repo,
-                              struct rev_cmdline_info *cmd_info,
-                              const char *onto_name,
-                              char **advance_name,
-                              struct commit **onto,
-                              struct strset **update_refs)
-{
-       struct ref_info rinfo;
-
-       get_ref_information(repo, cmd_info, &rinfo);
-       if (!rinfo.positive_refexprs)
-               die(_("need some commits to replay"));
-
-       die_for_incompatible_opt2(!!onto_name, "--onto",
-                                 !!*advance_name, "--advance");
-       if (onto_name) {
-               *onto = peel_committish(repo, onto_name, "--onto");
-               if (rinfo.positive_refexprs <
-                   strset_get_size(&rinfo.positive_refs))
-                       die(_("all positive revisions given must be references"));
-               *update_refs = xcalloc(1, sizeof(**update_refs));
-               **update_refs = rinfo.positive_refs;
-               memset(&rinfo.positive_refs, 0, sizeof(**update_refs));
-       } else {
-               struct object_id oid;
-               char *fullname = NULL;
-
-               if (!*advance_name)
-                       BUG("expected either onto_name or *advance_name in this function");
-
-               if (repo_dwim_ref(repo, *advance_name, strlen(*advance_name),
-                            &oid, &fullname, 0) == 1) {
-                       free(*advance_name);
-                       *advance_name = fullname;
-               } else {
-                       die(_("argument to --advance must be a reference"));
-               }
-               *onto = peel_committish(repo, *advance_name, "--advance");
-               if (rinfo.positive_refexprs > 1)
-                       die(_("cannot advance target with multiple sources because ordering would be ill-defined"));
-       }
-       strset_clear(&rinfo.negative_refs);
-       strset_clear(&rinfo.positive_refs);
-}
-
-static struct commit *mapped_commit(kh_oid_map_t *replayed_commits,
-                                   struct commit *commit,
-                                   struct commit *fallback)
-{
-       khint_t pos = kh_get_oid_map(replayed_commits, commit->object.oid);
-       if (pos == kh_end(replayed_commits))
-               return fallback;
-       return kh_value(replayed_commits, pos);
-}
-
-static struct commit *pick_regular_commit(struct repository *repo,
-                                         struct commit *pickme,
-                                         kh_oid_map_t *replayed_commits,
-                                         struct commit *onto,
-                                         struct merge_options *merge_opt,
-                                         struct merge_result *result)
-{
-       struct commit *base, *replayed_base;
-       struct tree *pickme_tree, *base_tree;
-
-       base = pickme->parents->item;
-       replayed_base = mapped_commit(replayed_commits, base, onto);
-
-       result->tree = repo_get_commit_tree(repo, replayed_base);
-       pickme_tree = repo_get_commit_tree(repo, pickme);
-       base_tree = repo_get_commit_tree(repo, base);
-
-       merge_opt->branch1 = short_commit_name(repo, replayed_base);
-       merge_opt->branch2 = short_commit_name(repo, pickme);
-       merge_opt->ancestor = xstrfmt("parent of %s", merge_opt->branch2);
-
-       merge_incore_nonrecursive(merge_opt,
-                                 base_tree,
-                                 result->tree,
-                                 pickme_tree,
-                                 result);
-
-       free((char*)merge_opt->ancestor);
-       merge_opt->ancestor = NULL;
-       if (!result->clean)
-               return NULL;
-       return create_commit(repo, result->tree, pickme, replayed_base);
-}
-
 static enum ref_action_mode parse_ref_action_mode(const char *ref_action, const char *source)
 {
        if (!ref_action || !strcmp(ref_action, "update"))
@@ -278,137 +43,6 @@ static enum ref_action_mode get_ref_action_mode(struct repository *repo, const c
        return REF_ACTION_UPDATE;
 }
 
-struct replay_revisions_options {
-       const char *advance;
-       const char *onto;
-       int contained;
-};
-
-struct replay_result {
-       struct replay_ref_update {
-               char *refname;
-               struct object_id old_oid;
-               struct object_id new_oid;
-       } *updates;
-       size_t updates_nr, updates_alloc;
-
-       bool merge_conflict;
-};
-
-static void replay_result_release(struct replay_result *result)
-{
-       for (size_t i = 0; i < result->updates_nr; i++)
-               free(result->updates[i].refname);
-       free(result->updates);
-}
-
-static void replay_result_queue_update(struct replay_result *result,
-                                      const char *refname,
-                                      const struct object_id *old_oid,
-                                      const struct object_id *new_oid)
-{
-       ALLOC_GROW(result->updates, result->updates_nr + 1, result->updates_alloc);
-       result->updates[result->updates_nr].refname = xstrdup(refname);
-       result->updates[result->updates_nr].old_oid = *old_oid;
-       result->updates[result->updates_nr].new_oid = *new_oid;
-       result->updates_nr++;
-}
-
-static int replay_revisions(struct repository *repo, struct rev_info *revs,
-                           struct replay_revisions_options *opts,
-                           struct replay_result *out)
-{
-       kh_oid_map_t *replayed_commits = NULL;
-       struct strset *update_refs = NULL;
-       struct commit *last_commit = NULL;
-       struct commit *commit;
-       struct commit *onto = NULL;
-       struct merge_options merge_opt;
-       struct merge_result result;
-       char *advance;
-       int ret;
-
-       advance = xstrdup_or_null(opts->advance);
-       set_up_replay_mode(repo, &revs->cmdline, opts->onto, &advance,
-                          &onto, &update_refs);
-
-       /* FIXME: Should allow replaying commits with the first as a root commit */
-
-       if (prepare_revision_walk(revs) < 0) {
-               ret = error(_("error preparing revisions"));
-               goto out;
-       }
-
-       init_basic_merge_options(&merge_opt, repo);
-       memset(&result, 0, sizeof(result));
-       merge_opt.show_rename_progress = 0;
-       last_commit = onto;
-       replayed_commits = kh_init_oid_map();
-       while ((commit = get_revision(revs))) {
-               const struct name_decoration *decoration;
-               khint_t pos;
-               int hr;
-
-               if (!commit->parents)
-                       die(_("replaying down from root commit is not supported yet!"));
-               if (commit->parents->next)
-                       die(_("replaying merge commits is not supported yet!"));
-
-               last_commit = pick_regular_commit(repo, commit, replayed_commits,
-                                                 onto, &merge_opt, &result);
-               if (!last_commit)
-                       break;
-
-               /* Record commit -> last_commit mapping */
-               pos = kh_put_oid_map(replayed_commits, commit->object.oid, &hr);
-               if (hr == 0)
-                       BUG("Duplicate rewritten commit: %s\n",
-                           oid_to_hex(&commit->object.oid));
-               kh_value(replayed_commits, pos) = last_commit;
-
-               /* Update any necessary branches */
-               if (advance)
-                       continue;
-               decoration = get_name_decoration(&commit->object);
-               if (!decoration)
-                       continue;
-               while (decoration) {
-                       if (decoration->type == DECORATION_REF_LOCAL &&
-                           (opts->contained || strset_contains(update_refs,
-                                                               decoration->name))) {
-                               replay_result_queue_update(out, decoration->name,
-                                                          &commit->object.oid,
-                                                          &last_commit->object.oid);
-                       }
-                       decoration = decoration->next;
-               }
-       }
-
-       if (!result.clean) {
-               out->merge_conflict = true;
-               ret = -1;
-               goto out;
-       }
-
-       /* In --advance mode, advance the target ref */
-       if (advance)
-               replay_result_queue_update(out, advance,
-                                          &onto->object.oid,
-                                          &last_commit->object.oid);
-
-       ret = 0;
-
-out:
-       if (update_refs) {
-               strset_clear(update_refs);
-               free(update_refs);
-       }
-       kh_destroy_oid_map(replayed_commits);
-       merge_finalize(&merge_opt, &result);
-       free(advance);
-       return ret;
-}
-
 static int handle_ref_update(enum ref_action_mode mode,
                             struct ref_transaction *transaction,
                             const char *refname,
meson.build +1 -0
index dd52efd1c8..a5a4e99b25 100644
@@ -471,6 +471,7 @@ libgit_sources = [
   'repack-midx.c',
   'repack-promisor.c',
   'replace-object.c',
+  'replay.c',
   'repo-settings.c',
   'repository.c',
   'rerere.c',
replay.c new file +0 -0
new file mode 100644
index 0000000000..fc7186ef09

replay.c line 9

Quoted 9 lines
replay.c new file +9 -0
@@ -0,0 +1,355 @@
+#define USE_THE_REPOSITORY_VARIABLE
+#define DISABLE_SIGN_COMPARE_WARNINGS
+
+#include "git-compat-util.h"
+#include "environment.h"
+#include "hex.h"
+#include "merge-ort.h"
+#include "object-name.h"
+#include "oidset.h"

I don't think oidset is used here? Although, come to think of it,
I'm not sure it was used in replay to begin with. Looks like I added this include during the switch from t/helper/test-fast-rebase, but never used it even then. I must have thought I was going to use it, and added it, but never did. Anyway, maybe this is a good time to get rid of it?

replay.c line 10

Quoted 1 line
replay.c new file +1 -0
+#include "parse-options.h"

Why would parse-options be included here? Oh, die_for_incompatible_opt2()? Feels a little weird that we have option parsing logic outside of builtin/, but...maybe it's all fine?

replay.c line 13

Quoted 3 lines
replay.c new file +3 -0
+#include "refs.h"
+#include "replay.h"
+#include "revision.h"

Shouldn't strmap.h (for strset) also be included? I think we get it as a side-effect of something else, but since we use it directly, it'd make sense to include directly.

Quoted 401 lines
replay.c new file +342 -0
+#include "tree.h"
+
+static const char *short_commit_name(struct repository *repo,
+                                    struct commit *commit)
+{
+       return repo_find_unique_abbrev(repo, &commit->object.oid,
+                                      DEFAULT_ABBREV);
+}
+
+static struct commit *peel_committish(struct repository *repo,
+                                     const char *name,
+                                     const char *mode)
+{
+       struct object *obj;
+       struct object_id oid;
+
+       if (repo_get_oid(repo, name, &oid))
+               die(_("'%s' is not a valid commit-ish for %s"), name, mode);
+       obj = parse_object_or_die(repo, &oid, name);
+       return (struct commit *)repo_peel_to_type(repo, name, 0, obj,
+                                                 OBJ_COMMIT);
+}
+
+static char *get_author(const char *message)
+{
+       size_t len;
+       const char *a;
+
+       a = find_commit_header(message, "author", &len);
+       if (a)
+               return xmemdupz(a, len);
+
+       return NULL;
+}
+
+static struct commit *create_commit(struct repository *repo,
+                                   struct tree *tree,
+                                   struct commit *based_on,
+                                   struct commit *parent)
+{
+       struct object_id ret;
+       struct object *obj = NULL;
+       struct commit_list *parents = NULL;
+       char *author;
+       char *sign_commit = NULL; /* FIXME: cli users might want to sign again */
+       struct commit_extra_header *extra = NULL;
+       struct strbuf msg = STRBUF_INIT;
+       const char *out_enc = get_commit_output_encoding();
+       const char *message = repo_logmsg_reencode(repo, based_on,
+                                                  NULL, out_enc);
+       const char *orig_message = NULL;
+       const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
+
+       commit_list_insert(parent, &parents);
+       extra = read_commit_extra_headers(based_on, exclude_gpgsig);
+       find_commit_subject(message, &orig_message);
+       strbuf_addstr(&msg, orig_message);
+       author = get_author(message);
+       reset_ident_date();
+       if (commit_tree_extended(msg.buf, msg.len, &tree->object.oid, parents,
+                                &ret, author, NULL, sign_commit, extra)) {
+               error(_("failed to write commit object"));
+               goto out;
+       }
+
+       obj = parse_object(repo, &ret);
+
+out:
+       repo_unuse_commit_buffer(the_repository, based_on, message);
+       free_commit_extra_headers(extra);
+       free_commit_list(parents);
+       strbuf_release(&msg);
+       free(author);
+       return (struct commit *)obj;
+}
+
+struct ref_info {
+       struct commit *onto;
+       struct strset positive_refs;
+       struct strset negative_refs;
+       int positive_refexprs;
+       int negative_refexprs;
+};
+
+static void get_ref_information(struct repository *repo,
+                               struct rev_cmdline_info *cmd_info,
+                               struct ref_info *ref_info)
+{
+       int i;
+
+       ref_info->onto = NULL;
+       strset_init(&ref_info->positive_refs);
+       strset_init(&ref_info->negative_refs);
+       ref_info->positive_refexprs = 0;
+       ref_info->negative_refexprs = 0;
+
+       /*
+        * When the user specifies e.g.
+        *   git replay origin/main..mybranch
+        *   git replay ^origin/next mybranch1 mybranch2
+        * we want to be able to determine where to replay the commits.  In
+        * these examples, the branches are probably based on an old version
+        * of either origin/main or origin/next, so we want to replay on the
+        * newest version of that branch.  In contrast we would want to error
+        * out if they ran
+        *   git replay ^origin/master ^origin/next mybranch
+        *   git replay mybranch~2..mybranch
+        * the first of those because there's no unique base to choose, and
+        * the second because they'd likely just be replaying commits on top
+        * of the same commit and not making any difference.
+        */
+       for (i = 0; i < cmd_info->nr; i++) {
+               struct rev_cmdline_entry *e = cmd_info->rev + i;
+               struct object_id oid;
+               const char *refexpr = e->name;
+               char *fullname = NULL;
+               int can_uniquely_dwim = 1;
+
+               if (*refexpr == '^')
+                       refexpr++;
+               if (repo_dwim_ref(repo, refexpr, strlen(refexpr), &oid, &fullname, 0) != 1)
+                       can_uniquely_dwim = 0;
+
+               if (e->flags & BOTTOM) {
+                       if (can_uniquely_dwim)
+                               strset_add(&ref_info->negative_refs, fullname);
+                       if (!ref_info->negative_refexprs)
+                               ref_info->onto = lookup_commit_reference_gently(repo,
+                                                                               &e->item->oid, 1);
+                       ref_info->negative_refexprs++;
+               } else {
+                       if (can_uniquely_dwim)
+                               strset_add(&ref_info->positive_refs, fullname);
+                       ref_info->positive_refexprs++;
+               }
+
+               free(fullname);
+       }
+}
+
+static void set_up_replay_mode(struct repository *repo,
+                              struct rev_cmdline_info *cmd_info,
+                              const char *onto_name,
+                              char **advance_name,
+                              struct commit **onto,
+                              struct strset **update_refs)
+{
+       struct ref_info rinfo;
+
+       get_ref_information(repo, cmd_info, &rinfo);
+       if (!rinfo.positive_refexprs)
+               die(_("need some commits to replay"));
+
+       die_for_incompatible_opt2(!!onto_name, "--onto",
+                                 !!*advance_name, "--advance");
+       if (onto_name) {
+               *onto = peel_committish(repo, onto_name, "--onto");
+               if (rinfo.positive_refexprs <
+                   strset_get_size(&rinfo.positive_refs))
+                       die(_("all positive revisions given must be references"));
+               *update_refs = xcalloc(1, sizeof(**update_refs));
+               **update_refs = rinfo.positive_refs;
+               memset(&rinfo.positive_refs, 0, sizeof(**update_refs));
+       } else {
+               struct object_id oid;
+               char *fullname = NULL;
+
+               if (!*advance_name)
+                       BUG("expected either onto_name or *advance_name in this function");
+
+               if (repo_dwim_ref(repo, *advance_name, strlen(*advance_name),
+                            &oid, &fullname, 0) == 1) {
+                       free(*advance_name);
+                       *advance_name = fullname;
+               } else {
+                       die(_("argument to --advance must be a reference"));
+               }
+               *onto = peel_committish(repo, *advance_name, "--advance");
+               if (rinfo.positive_refexprs > 1)
+                       die(_("cannot advance target with multiple sources because ordering would be ill-defined"));
+       }
+       strset_clear(&rinfo.negative_refs);
+       strset_clear(&rinfo.positive_refs);
+}
+
+static struct commit *mapped_commit(kh_oid_map_t *replayed_commits,
+                                   struct commit *commit,
+                                   struct commit *fallback)
+{
+       khint_t pos = kh_get_oid_map(replayed_commits, commit->object.oid);
+       if (pos == kh_end(replayed_commits))
+               return fallback;
+       return kh_value(replayed_commits, pos);
+}
+
+static struct commit *pick_regular_commit(struct repository *repo,
+                                         struct commit *pickme,
+                                         kh_oid_map_t *replayed_commits,
+                                         struct commit *onto,
+                                         struct merge_options *merge_opt,
+                                         struct merge_result *result)
+{
+       struct commit *base, *replayed_base;
+       struct tree *pickme_tree, *base_tree;
+
+       base = pickme->parents->item;
+       replayed_base = mapped_commit(replayed_commits, base, onto);
+
+       result->tree = repo_get_commit_tree(repo, replayed_base);
+       pickme_tree = repo_get_commit_tree(repo, pickme);
+       base_tree = repo_get_commit_tree(repo, base);
+
+       merge_opt->branch1 = short_commit_name(repo, replayed_base);
+       merge_opt->branch2 = short_commit_name(repo, pickme);
+       merge_opt->ancestor = xstrfmt("parent of %s", merge_opt->branch2);
+
+       merge_incore_nonrecursive(merge_opt,
+                                 base_tree,
+                                 result->tree,
+                                 pickme_tree,
+                                 result);
+
+       free((char*)merge_opt->ancestor);
+       merge_opt->ancestor = NULL;
+       if (!result->clean)
+               return NULL;
+       return create_commit(repo, result->tree, pickme, replayed_base);
+}
+
+void replay_result_release(struct replay_result *result)
+{
+       for (size_t i = 0; i < result->updates_nr; i++)
+               free(result->updates[i].refname);
+       free(result->updates);
+}
+
+static void replay_result_queue_update(struct replay_result *result,
+                                      const char *refname,
+                                      const struct object_id *old_oid,
+                                      const struct object_id *new_oid)
+{
+       ALLOC_GROW(result->updates, result->updates_nr + 1, result->updates_alloc);
+       result->updates[result->updates_nr].refname = xstrdup(refname);
+       result->updates[result->updates_nr].old_oid = *old_oid;
+       result->updates[result->updates_nr].new_oid = *new_oid;
+       result->updates_nr++;
+}
+
+int replay_revisions(struct repository *repo, struct rev_info *revs,
+                    struct replay_revisions_options *opts,
+                    struct replay_result *out)
+{
+       kh_oid_map_t *replayed_commits = NULL;
+       struct strset *update_refs = NULL;
+       struct commit *last_commit = NULL;
+       struct commit *commit;
+       struct commit *onto = NULL;
+       struct merge_options merge_opt;
+       struct merge_result result;
+       char *advance;
+       int ret;
+
+       advance = xstrdup_or_null(opts->advance);
+       set_up_replay_mode(repo, &revs->cmdline, opts->onto, &advance,
+                          &onto, &update_refs);
+
+       /* FIXME: Should allow replaying commits with the first as a root commit */
+
+       if (prepare_revision_walk(revs) < 0) {
+               ret = error(_("error preparing revisions"));
+               goto out;
+       }
+
+       init_basic_merge_options(&merge_opt, repo);
+       memset(&result, 0, sizeof(result));
+       merge_opt.show_rename_progress = 0;
+       last_commit = onto;
+       replayed_commits = kh_init_oid_map();
+       while ((commit = get_revision(revs))) {
+               const struct name_decoration *decoration;
+               khint_t pos;
+               int hr;
+
+               if (!commit->parents)
+                       die(_("replaying down from root commit is not supported yet!"));
+               if (commit->parents->next)
+                       die(_("replaying merge commits is not supported yet!"));
+
+               last_commit = pick_regular_commit(repo, commit, replayed_commits,
+                                                 onto, &merge_opt, &result);
+               if (!last_commit)
+                       break;
+
+               /* Record commit -> last_commit mapping */
+               pos = kh_put_oid_map(replayed_commits, commit->object.oid, &hr);
+               if (hr == 0)
+                       BUG("Duplicate rewritten commit: %s\n",
+                           oid_to_hex(&commit->object.oid));
+               kh_value(replayed_commits, pos) = last_commit;
+
+               /* Update any necessary branches */
+               if (advance)
+                       continue;
+               decoration = get_name_decoration(&commit->object);
+               if (!decoration)
+                       continue;
+               while (decoration) {
+                       if (decoration->type == DECORATION_REF_LOCAL &&
+                           (opts->contained || strset_contains(update_refs,
+                                                               decoration->name))) {
+                               replay_result_queue_update(out, decoration->name,
+                                                          &commit->object.oid,
+                                                          &last_commit->object.oid);
+                       }
+                       decoration = decoration->next;
+               }
+       }
+
+       if (!result.clean) {
+               out->merge_conflict = true;
+               ret = -1;
+               goto out;
+       }
+
+       /* In --advance mode, advance the target ref */
+       if (advance)
+               replay_result_queue_update(out, advance,
+                                          &onto->object.oid,
+                                          &last_commit->object.oid);
+
+       ret = 0;
+
+out:
+       if (update_refs) {
+               strset_clear(update_refs);
+               free(update_refs);
+       }
+       kh_destroy_oid_map(replayed_commits);
+       merge_finalize(&merge_opt, &result);
+       free(advance);
+       return ret;
+}
replay.h new file +53 -0
new file mode 100644
index 0000000000..84bc8a7a5b
@@ -0,0 +1,64 @@
+#ifndef REPLAY_H
+#define REPLAY_H
+
+#include "hash.h"
+
+struct repository;
+struct rev_info;
+
+/*
+ * A set of options that can be passed to `replay_revisions()`.
+ */
+struct replay_revisions_options {
+       /*
+        * Starting point at which to create the new commits; must be a branch
+        * name. The branch will be updated to point to the rewritten commits.
+        * This option is mutually exclusive with `onto`.
+        */
+       const char *advance;
+
+       /*
+        * Starting point at which to create the new commits; must be a
+        * committish. References pointing at decendants of `onto` will be
+        * updated to point to the new commits.
+        */
+        const char *onto;
+
+       /*
+        * Update branches that point at commits in the given revision range.
+        * Requires `onto` to be set.
+        */
+       int contained;
+};
+
+/* This struct is used as an out-parameter by `replay_revisions()`. */
+struct replay_result {
+       /*
+        * The set of reference updates that are caused by replaying the
+        * commits.
+        */
+       struct replay_ref_update {
+               char *refname;
+               struct object_id old_oid;
+               struct object_id new_oid;
+       } *updates;
+       size_t updates_nr, updates_alloc;
+
+       /* Set to true in case the replay failed with a merge conflict. */
+       bool merge_conflict;
+};
+
+void replay_result_release(struct replay_result *result);
+
+/*

replay.h line 63

Quoted 10 lines
replay.h new file +10 -0
+ * Replay a set of commits onto a new location. Leaves both the working tree,
+ * index and references untouched. Reference updates caused by the replay will
+ * be recorded in the `updates` out pointer.
+ *
+ * Returns 0 on success, a negative error code otherwise.
+ */
+int replay_revisions(struct repository *repo, struct rev_info *revs,
+                    struct replay_revisions_options *opts,
+                    struct replay_result *out);
+

stray extra line?

replay.h line 64

Quoted 1 line
replay.h new file +1 -0
+#endif

It feels duplicative to have replay_result include a merge_conflict field and to have replay_revisions() return an int which signifies whether there's a conflict. Can we remove one of the two? (Perhaps the merge_conflict field was only a workaround to the weird ret setting from the previous patch?)

#305 lore raw

Re: [PATCH v9 2/7] builtin/replay: move core logic into "libgit.a"

Quoted 15 lines · Elijah Newren
Quoted 14 lines · Patrick Steinhardt
replay.c new file +8 -0
new file mode 100644
index 0000000000..fc7186ef09
@@ -0,0 +1,355 @@
+#define USE_THE_REPOSITORY_VARIABLE
+#define DISABLE_SIGN_COMPARE_WARNINGS
+
+#include "git-compat-util.h"
+#include "environment.h"
+#include "hex.h"
+#include "merge-ort.h"
+#include "object-name.h"
Quoted 8 lines

replay.c line 9

Quoted 1 line
replay.c new file +1 -0
+#include "oidset.h"

I don't think oidset is used here? Although, come to think of it,
I'm not sure it was used in replay to begin with. Looks like I added this include during the switch from t/helper/test-fast-rebase, but never used it even then. I must have thought I was going to use it, and added it, but never did. Anyway, maybe this is a good time to get rid of it?

Yeah, let's.

Quoted 5 lines

replay.c line 10

Quoted 1 line
replay.c new file +1 -0
+#include "parse-options.h"

Why would parse-options be included here? Oh, die_for_incompatible_opt2()? Feels a little weird that we have option parsing logic outside of builtin/, but...maybe it's all fine?

I'm not a huge fan of it, either. We could for example change this so that we BUG() here and instead have the option in "builtin/replay.c"? Something like this:

builtin/replay.c +5 -5
index 4a11ef0f1b..649c93200e 100644
@@ -177,8 +177,9 @@ static void set_up_replay_mode(struct repository *repo,
 	if (!rinfo.positive_refexprs)
 		die(_("need some commits to replay"));
 
-	die_for_incompatible_opt2(!!onto_name, "--onto",
-				  !!*advance_name, "--advance");
+	if (!(!!onto_name ^ !!*advance_name))
+		BUG("expected either onto_name or *advance_name in this function");
+
 	if (onto_name) {
 		*onto = peel_committish(repo, onto_name, "--onto");
 		if (rinfo.positive_refexprs <
@@ -191,9 +192,6 @@ static void set_up_replay_mode(struct repository *repo,
 		struct object_id oid;
 		char *fullname = NULL;
 
-		if (!*advance_name)
-			BUG("expected either onto_name or *advance_name in this function");
-
 		if (repo_dwim_ref(repo, *advance_name, strlen(*advance_name),
 			     &oid, &fullname, 0) == 1) {
 			free(*advance_name);
@@ -478,6 +476,8 @@ int cmd_replay(int argc,
 
 	die_for_incompatible_opt2(!!opts.advance, "--advance",
 				  opts.contained, "--contained");
+	die_for_incompatible_opt2(!!opts.advance, "--advance",
+				  !!opts.onto, "--onto");
 
 	/* Parse ref action mode from command line or config */
 	ref_mode = get_ref_action_mode(repo, ref_action);

Yeha, I think that's cleaner, even if it repeats some of the conditionals.

Quoted 7 lines

replay.c line 13

Quoted 3 lines
replay.c new file +3 -0
+#include "refs.h"
+#include "replay.h"
+#include "revision.h"

Shouldn't strmap.h (for strset) also be included? I think we get it as a side-effect of something else, but since we use it directly, it'd make sense to include directly.

Yup, will add.

Quoted 63 lines
Quoted 63 lines
replay.h new file +57 -0
new file mode 100644
index 0000000000..84bc8a7a5b
@@ -0,0 +1,64 @@
+#ifndef REPLAY_H
+#define REPLAY_H
+
+#include "hash.h"
+
+struct repository;
+struct rev_info;
+
+/*
+ * A set of options that can be passed to `replay_revisions()`.
+ */
+struct replay_revisions_options {
+       /*
+        * Starting point at which to create the new commits; must be a branch
+        * name. The branch will be updated to point to the rewritten commits.
+        * This option is mutually exclusive with `onto`.
+        */
+       const char *advance;
+
+       /*
+        * Starting point at which to create the new commits; must be a
+        * committish. References pointing at decendants of `onto` will be
+        * updated to point to the new commits.
+        */
+        const char *onto;
+
+       /*
+        * Update branches that point at commits in the given revision range.
+        * Requires `onto` to be set.
+        */
+       int contained;
+};
+
+/* This struct is used as an out-parameter by `replay_revisions()`. */
+struct replay_result {
+       /*
+        * The set of reference updates that are caused by replaying the
+        * commits.
+        */
+       struct replay_ref_update {
+               char *refname;
+               struct object_id old_oid;
+               struct object_id new_oid;
+       } *updates;
+       size_t updates_nr, updates_alloc;
+
+       /* Set to true in case the replay failed with a merge conflict. */
+       bool merge_conflict;
+};
+
+void replay_result_release(struct replay_result *result);
+
+/*
+ * Replay a set of commits onto a new location. Leaves both the working tree,
+ * index and references untouched. Reference updates caused by the replay will
+ * be recorded in the `updates` out pointer.
+ *
Quoted 8 lines

replay.h line 63

Quoted 6 lines
replay.h new file +6 -0
+ * Returns 0 on success, a negative error code otherwise.
+ */
+int replay_revisions(struct repository *repo, struct rev_info *revs,
+                    struct replay_revisions_options *opts,
+                    struct replay_result *out);
+

stray extra line?

We typically have an empty line between the last declaration and the #endif in our headers.

Quoted 7 lines

replay.h line 64

Quoted 1 line
replay.h new file +1 -0
+#endif

It feels duplicative to have replay_result include a merge_conflict field and to have replay_revisions() return an int which signifies whether there's a conflict. Can we remove one of the two? (Perhaps the merge_conflict field was only a workaround to the weird ret setting from the previous patch?)

The idea here is that we have a generic error code that tells the caller that _something_ happened, whereas struct replay_result gives the caller a bit more context around what exactly has happened. This allows callers to handle merge conflicts differently from any other error and makes the different failure modes a lot more explicit.

Some context: at GitLab we actually have the use case to surface more information around what commits have conflicted, so there will be a follow-up patch series that extends struct replay_result to return more information about the actual conflict. I'm already planning ahead a bit in this patch series.

Patrick

#306 lore raw

Re: [PATCH v9 2/7] builtin/replay: move core logic into "libgit.a"

Quoted 2 lines · Patrick Steinhardt

On Fri, Jan 09, 2026 at 05:16:41PM -0800, Elijah Newren wrote:

[...]

Quoted 9 lines
Quoted 6 lines

Review

Quoted 4 lines
(quoted diff) +4 -0
+int replay_revisions(struct repository *repo, struct rev_info *revs,
+                    struct replay_revisions_options *opts,
+                    struct replay_result *out);
+

stray extra line?

We typically have an empty line between the last declaration and the #endif in our headers.

Yeah, I was just confused; sorry.

Quoted 8 lines
Quoted 7 lines
Quoted 1 line

+#endif

It feels duplicative to have replay_result include a merge_conflict field and to have replay_revisions() return an int which signifies whether there's a conflict. Can we remove one of the two? (Perhaps the merge_conflict field was only a workaround to the weird ret setting from the previous patch?)

Quoted 8 lines

The idea here is that we have a generic error code that tells the caller that _something_ happened, whereas struct replay_result gives the caller a bit more context around what exactly has happened. This allows callers to handle merge conflicts differently from any other error and makes the different failure modes a lot more explicit.

Some context: at GitLab we actually have the use case to surface more information around what commits have conflicted, so there will be a

Interesting, but doesn't answering that question presume first-class conflict handling? How do you determine which commits conflict without that? Or, is the first commit we process that hits a conflict sufficient information and you don't really need the commits that conflict, just one of them? Or, do you presume that all unprocessed commits after the first one that conflicted would have also conflicted (even if it touched files that are conflict-free so far, so that commit would not have contributed to the conflicts)? If this is done without first-class conflict handling, there may also be an assumption here about linear single-branch history, or else some kind of attempt to continue processing whichever commits don't have an ancestor that has conflicted, so that we can enumerate "commits [which] have conflicted".

Quoted 3 lines

follow-up patch series that extends struct replay_result to return more information about the actual conflict. I'm already planning ahead a bit in this patch series.

Wait, above you said you wanted to know the "commits [which] have conflicted", here you seem to be suggesting you want to know about "the actual conflict" which might mean you only care about the first commit that conflicted but you want details about what conflicted within it. Or is it perhaps the set of files that would have had conflicts across replaying the whole sequence of patches (in which case a bunch of the previous questions are still valid)?

#307 lore raw

Re: [PATCH v9 2/7] builtin/replay: move core logic into "libgit.a"

Quoted 19 lines · Elijah Newren
Quoted 2 lines · Patrick Steinhardt

On Fri, Jan 09, 2026 at 05:16:41PM -0800, Elijah Newren wrote:

[...]

Quoted 6 lines
Quoted 5 lines

It feels duplicative to have replay_result include a merge_conflict field and to have replay_revisions() return an int which signifies whether there's a conflict. Can we remove one of the two? (Perhaps the merge_conflict field was only a workaround to the weird ret setting from the previous patch?)

Quoted 8 lines

The idea here is that we have a generic error code that tells the caller that _something_ happened, whereas struct replay_result gives the caller a bit more context around what exactly has happened. This allows callers to handle merge conflicts differently from any other error and makes the different failure modes a lot more explicit.

Some context: at GitLab we actually have the use case to surface more information around what commits have conflicted, so there will be a

Quoted 13 lines

Interesting, but doesn't answering that question presume first-class conflict handling? How do you determine which commits conflict without that? Or, is the first commit we process that hits a conflict sufficient information and you don't really need the commits that conflict, just one of them? Or, do you presume that all unprocessed commits after the first one that conflicted would have also conflicted (even if it touched files that are conflict-free so far, so that commit would not have contributed to the conflicts)? If this is done without first-class conflict handling, there may also be an assumption here about linear single-branch history, or else some kind of attempt to continue processing whichever commits don't have an ancestor that has conflicted, so that we can enumerate "commits [which] have conflicted".

Yup, knowing about the first commit that conflicts is sufficient for our use case.

Quoted 11 lines
Quoted 3 lines

follow-up patch series that extends struct replay_result to return more information about the actual conflict. I'm already planning ahead a bit in this patch series.

Wait, above you said you wanted to know the "commits [which] have conflicted", here you seem to be suggesting you want to know about "the actual conflict" which might mean you only care about the first commit that conflicted but you want details about what conflicted within it. Or is it perhaps the set of files that would have had conflicts across replaying the whole sequence of patches (in which case a bunch of the previous questions are still valid)?

I was simply being inaccurate there, we only care about the first conflicting commit, no plural.

Thanks!

Patrick

#308 lore raw

PATCH v9 3/7 replay: small set of cleanups

In reply to Patrick Steinhardt

Perform a small set of cleanups so that the "replay" logic compiles with "-Wsign-compare" and doesn't use the_repository anymore. Note that there are still some implicit dependencies on the_repository, e.g. because we use get_commit_output_encoding().

---
 replay.c | 11 ++++-------
 1 file changed, 4 insertions(+), 7 deletions(-)
replay.c +4 -7
index fc7186ef09..313fb2a768 100644
@@ -1,5 +1,4 @@
 #define USE_THE_REPOSITORY_VARIABLE
-#define DISABLE_SIGN_COMPARE_WARNINGS
 
 #include "git-compat-util.h"
 #include "environment.h"
@@ -79,7 +78,7 @@ static struct commit *create_commit(struct repository *repo,
 	obj = parse_object(repo, &ret);
 
 out:
-	repo_unuse_commit_buffer(the_repository, based_on, message);
+	repo_unuse_commit_buffer(repo, based_on, message);
 	free_commit_extra_headers(extra);
 	free_commit_list(parents);
 	strbuf_release(&msg);
@@ -91,16 +90,14 @@ struct ref_info {
 	struct commit *onto;
 	struct strset positive_refs;
 	struct strset negative_refs;
-	int positive_refexprs;
-	int negative_refexprs;
+	size_t positive_refexprs;
+	size_t negative_refexprs;
 };
 
 static void get_ref_information(struct repository *repo,
 				struct rev_cmdline_info *cmd_info,
 				struct ref_info *ref_info)
 {
-	int i;
-
 	ref_info->onto = NULL;
 	strset_init(&ref_info->positive_refs);
 	strset_init(&ref_info->negative_refs);
@@ -122,7 +119,7 @@ static void get_ref_information(struct repository *repo,
 	 * the second because they'd likely just be replaying commits on top
 	 * of the same commit and not making any difference.
 	 */
-	for (i = 0; i < cmd_info->nr; i++) {
+	for (size_t i = 0; i < cmd_info->nr; i++) {
 		struct rev_cmdline_entry *e = cmd_info->rev + i;
 		struct object_id oid;
 		const char *refexpr = e->name;
Signature · 1 line
2.52.0.542.g9473a8513b.dirty
#309 lore raw

PATCH v9 4/7 replay: yield the object ID of the final rewritten commit

In reply to Patrick Steinhardt

In a subsequent commit we'll introduce a new git-history(1) command that uses the replay machinery to rewrite commits. One of its supported modes will only want to update the "HEAD" reference, but that is not currently supported by the replay machinery.

Allow implementing this use case by exposing a final_oid field for the reference updates. This field will be set to the last commit that was rewritten, which is sufficient information for us to implement this mode in git-history(1).

---
 replay.c |  2 ++
 replay.h | 16 ++++++++++++++++
 2 files changed, 18 insertions(+)
replay.c +2 -0
index 313fb2a768..20560e792b 100644
@@ -338,6 +338,8 @@ int replay_revisions(struct repository *repo, struct rev_info *revs,
 					   &onto->object.oid,
 					   &last_commit->object.oid);
 
+	out->final_oid = last_commit->object.oid;
+
 	ret = 0;
 
 out:
replay.h +16 -0
index 84bc8a7a5b..f8f9889112 100644
@@ -46,6 +46,22 @@ struct replay_result {
 
 	/* Set to true in case the replay failed with a merge conflict. */
 	bool merge_conflict;
+
+	/*
+	 * The final object ID that was rewritten. Note that this field has
+	 * somewhat special semantics and may or may not be what you want:
+	 *
+	 *   - If no commits were rewritten it will remain uninitialized.
+	 *
+	 *   - If a thicket of branches is rewritten it is undefined in which
+	 *     order those branches will be rewritten, and thus the final object
+	 *     ID may point to a different commit than you'd expect.
+	 *
+	 * That being said, this field can still be useful when you know that
+	 * you only replay a single strand of commits. In that case, the final
+	 * commit will point to the tip of the rewritten strand of commits.
+	 */
+	struct object_id final_oid;
 };
 
 void replay_result_release(struct replay_result *result);
Signature · 1 line
2.52.0.542.g9473a8513b.dirty
#310 lore raw

Re: [PATCH v9 4/7] replay: yield the object ID of the final rewritten commit

Quoted 5 lines · Patrick Steinhardt

In a subsequent commit we'll introduce a new git-history(1) command that uses the replay machinery to rewrite commits. One of its supported modes will only want to update the "HEAD" reference, but that is not currently supported by the replay machinery.

I'm a little surprised. In that case replay_result->updates_nr would be 1 and you'd just use replay_result->updates[0], right?

Quoted 39 lines

Allow implementing this use case by exposing a final_oid field for the reference updates. This field will be set to the last commit that was rewritten, which is sufficient information for us to implement this mode in git-history(1).

---
 replay.c |  2 ++
 replay.h | 16 ++++++++++++++++
 2 files changed, 18 insertions(+)
replay.c +2 -0
index 313fb2a768..20560e792b 100644
@@ -338,6 +338,8 @@ int replay_revisions(struct repository *repo, struct rev_info *revs,
                                           &onto->object.oid,
                                           &last_commit->object.oid);
 
+       out->final_oid = last_commit->object.oid;
+
        ret = 0;
 
 out:
replay.h +7 -0
index 84bc8a7a5b..f8f9889112 100644
@@ -46,6 +46,22 @@ struct replay_result {
 
        /* Set to true in case the replay failed with a merge conflict. */
        bool merge_conflict;
+
+       /*
+        * The final object ID that was rewritten. Note that this field has
+        * somewhat special semantics and may or may not be what you want:
+        *
+        *   - If no commits were rewritten it will remain uninitialized.
+        *

replay.h struct replay_result { · line 65

Quoted 10 lines
replay.h +9 -0
+        *   - If a thicket of branches is rewritten it is undefined in which
+        *     order those branches will be rewritten, and thus the final object
+        *     ID may point to a different commit than you'd expect.
+        *
+        * That being said, this field can still be useful when you know that
+        * you only replay a single strand of commits. In that case, the final
+        * commit will point to the tip of the rewritten strand of commits.
+        */
+       struct object_id final_oid;
 };

I don't understand why this is needed for the usecase you provide. Are you perhaps trying to rewrite a set of commits whose tip is not a branch or something (directly contradicting your first paragraph of the commit message)? That's the only case I can think of where this would be useful, unless I'm missing something?

#311 lore raw

Re: [PATCH v9 4/7] replay: yield the object ID of the final rewritten commit

Quoted 24 lines · Elijah Newren
Quoted 23 lines · Patrick Steinhardt
replay.h +15 -0
index 84bc8a7a5b..f8f9889112 100644
@@ -46,6 +46,22 @@ struct replay_result {
 
        /* Set to true in case the replay failed with a merge conflict. */
        bool merge_conflict;
+
+       /*
+        * The final object ID that was rewritten. Note that this field has
+        * somewhat special semantics and may or may not be what you want:
+        *
+        *   - If no commits were rewritten it will remain uninitialized.
+        *
+        *   - If a thicket of branches is rewritten it is undefined in which
+        *     order those branches will be rewritten, and thus the final object
+        *     ID may point to a different commit than you'd expect.
+        *
+        * That being said, this field can still be useful when you know that
+        * you only replay a single strand of commits. In that case, the final
+        * commit will point to the tip of the rewritten strand of commits.
+        */
Quoted 8 lines

replay.h struct replay_result { · line 65

Quoted 2 lines
replay.h +1 -0
+       struct object_id final_oid;
 };

I don't understand why this is needed for the usecase you provide. Are you perhaps trying to rewrite a set of commits whose tip is not a branch or something (directly contradicting your first paragraph of the commit message)? That's the only case I can think of where this would be useful, unless I'm missing something?

It's the case where you're rewriting a detached HEAD. But I'll discard this commit in favor of what you've posted.

Thanks!

Patrick

#312 lore raw

PATCH v9 5/7 wt-status: provide function to expose status for trees

In reply to Patrick Steinhardt

The "wt-status" subsystem is responsible for printing status information around the current state of the working tree. This most importantly includes information around whether the working tree or the index have any changes.

We're about to introduce a new command where the changes in neither of them are actually relevant to us. Instead, what we want is to format the changes between two different trees. While it is a little bit of a stretch to add this as functionality to _working tree_ status, it doesn't make any sense to open-code this functionality, either.

Implement a new function wt_status_collect_changes_trees() that diffs two trees and formats the status accordingly. This function is not yet used, but will be in a subsequent commit.

---
 wt-status.c | 24 ++++++++++++++++++++++++
 wt-status.h |  9 +++++++++
 2 files changed, 33 insertions(+)
wt-status.c +24 -0
index e12adb26b9..95942399f8 100644
@@ -612,6 +612,30 @@ static void wt_status_collect_updated_cb(struct diff_queue_struct *q,
 	}
 }
 
+void wt_status_collect_changes_trees(struct wt_status *s,
+				     const struct object_id *old_treeish,
+				     const struct object_id *new_treeish)
+{
+	struct diff_options opts = { 0 };
+
+	repo_diff_setup(s->repo, &opts);
+	opts.output_format = DIFF_FORMAT_CALLBACK;
+	opts.format_callback = wt_status_collect_updated_cb;
+	opts.format_callback_data = s;
+	opts.detect_rename = s->detect_rename >= 0 ? s->detect_rename : opts.detect_rename;
+	opts.rename_limit = s->rename_limit >= 0 ? s->rename_limit : opts.rename_limit;
+	opts.rename_score = s->rename_score >= 0 ? s->rename_score : opts.rename_score;
+	opts.flags.recursive = 1;
+	diff_setup_done(&opts);
+
+	diff_tree_oid(old_treeish, new_treeish, "", &opts);
+	diffcore_std(&opts);
+	diff_flush(&opts);
+	wt_status_get_state(s->repo, &s->state, 0);
+
+	diff_free(&opts);
+}
+
 static void wt_status_collect_changes_worktree(struct wt_status *s)
 {
 	struct rev_info rev;
wt-status.h +9 -0
index e40a27214a..e9fe32e98c 100644
@@ -153,6 +153,15 @@ void wt_status_add_cut_line(struct wt_status *s);
 void wt_status_prepare(struct repository *r, struct wt_status *s);
 void wt_status_print(struct wt_status *s);
 void wt_status_collect(struct wt_status *s);
+
+/*
+ * Collect all changes between the two trees. Changes will be displayed as if
+ * they were staged into the index.
+ */
+void wt_status_collect_changes_trees(struct wt_status *s,
+				     const struct object_id *old_treeish,
+				     const struct object_id *new_treeish);
+
 /*
  * Frees the buffers allocated by wt_status_collect.
  */
Signature · 1 line
2.52.0.542.g9473a8513b.dirty
#313 lore raw

PATCH v9 6/7 builtin: add new "history" command

In reply to Patrick Steinhardt

When rewriting history via git-rebase(1) there are a few very common use cases:

- The ordering of two commits should be reversed.

- A commit should be split up into two commits.

- A commit should be dropped from the history completely.

- Multiple commits should be squashed into one.

- Editing an existing commit that is not the tip of the current branch.

While these operations are all doable, it often feels needlessly kludgey to do so by doing an interactive rebase, using the editor to say what one wants, and then perform the actions. Also, some operations like splitting up a commit into two are way more involved than that and require a whole series of commands.

Rebases also do not update dependent branches. The use of stacked branches has grown quite common with competing version control systems like Jujutsu though, so it clearly is a need that users have. While rebases _can_ serve this use case if one always works on the latest stacked branch, it is somewhat awkward and very easy to get wrong.

Add a new "history" command to plug these gaps. This command will have several different subcommands to imperatively rewrite history for common use cases like the above.

---
 .gitignore                     |  1 +
 Documentation/git-history.adoc | 56 ++++++++++++++++++++++++++++++++++++++++++
 Documentation/meson.build      |  1 +
 Makefile                       |  1 +
 builtin.h                      |  1 +
 builtin/history.c              | 22 +++++++++++++++++
 command-list.txt               |  1 +
 git.c                          |  1 +
 meson.build                    |  1 +
 t/meson.build                  |  1 +
 t/t3450-history.sh             | 17 +++++++++++++
 11 files changed, 103 insertions(+)
.gitignore +1 -0
index 78a45cb5be..24635cf2d6 100644
@@ -79,6 +79,7 @@
 /git-grep
 /git-hash-object
 /git-help
+/git-history
 /git-hook
 /git-http-backend
 /git-http-fetch
Documentation/git-history.adoc new file +56 -0

56 lines not on this page · raw message

Documentation/meson.build +1 -0
index f02dbc20cb..fd2e8cc02d 100644
@@ -64,6 +64,7 @@ manpages = {
   'git-gui.adoc' : 1,
   'git-hash-object.adoc' : 1,
   'git-help.adoc' : 1,
+  'git-history.adoc' : 1,
   'git-hook.adoc' : 1,
   'git-http-backend.adoc' : 1,
   'git-http-fetch.adoc' : 1,
Makefile +1 -0
index 1c64a5d2ae..c0569ed8e4 100644
@@ -1418,6 +1418,7 @@ BUILTIN_OBJS += builtin/get-tar-commit-id.o
 BUILTIN_OBJS += builtin/grep.o
 BUILTIN_OBJS += builtin/hash-object.o
 BUILTIN_OBJS += builtin/help.o
+BUILTIN_OBJS += builtin/history.o
 BUILTIN_OBJS += builtin/hook.o
 BUILTIN_OBJS += builtin/index-pack.o
 BUILTIN_OBJS += builtin/init-db.o
builtin.h +1 -0
index 1b35565fbd..93c91d07d4 100644
@@ -172,6 +172,7 @@ int cmd_get_tar_commit_id(int argc, const char **argv, const char *prefix, struc
 int cmd_grep(int argc, const char **argv, const char *prefix, struct repository *repo);
 int cmd_hash_object(int argc, const char **argv, const char *prefix, struct repository *repo);
 int cmd_help(int argc, const char **argv, const char *prefix, struct repository *repo);
+int cmd_history(int argc, const char **argv, const char *prefix, struct repository *repo);
 int cmd_hook(int argc, const char **argv, const char *prefix, struct repository *repo);
 int cmd_index_pack(int argc, const char **argv, const char *prefix, struct repository *repo);
 int cmd_init_db(int argc, const char **argv, const char *prefix, struct repository *repo);
builtin/history.c new file +22 -0
new file mode 100644
index 0000000000..f6fe32610b
@@ -0,0 +1,22 @@
+#include "builtin.h"
+#include "gettext.h"
+#include "parse-options.h"
+
+int cmd_history(int argc,
+		const char **argv,
+		const char *prefix,
+		struct repository *repo UNUSED)
+{
+	const char * const usage[] = {
+		N_("git history [<options>]"),
+		NULL,
+	};
+	struct option options[] = {
+		OPT_END(),
+	};
+
+	argc = parse_options(argc, argv, prefix, options, usage, 0);
+	if (argc)
+		usagef("unrecognized argument: %s", argv[0]);
+	return 0;
+}
command-list.txt +1 -0
index accd3d0c4b..f9005cf459 100644
@@ -115,6 +115,7 @@ git-grep                                mainporcelain           info
 git-gui                                 mainporcelain
 git-hash-object                         plumbingmanipulators
 git-help                                ancillaryinterrogators          complete
+git-history                             mainporcelain           history
 git-hook                                purehelpers
 git-http-backend                        synchingrepositories
 git-http-fetch                          synchelpers
git.c +1 -0
index c5fad56813..744cb6527e 100644
@@ -586,6 +586,7 @@ static struct cmd_struct commands[] = {
 	{ "grep", cmd_grep, RUN_SETUP_GENTLY },
 	{ "hash-object", cmd_hash_object },
 	{ "help", cmd_help },
+	{ "history", cmd_history, RUN_SETUP },
 	{ "hook", cmd_hook, RUN_SETUP },
 	{ "index-pack", cmd_index_pack, RUN_SETUP_GENTLY | NO_PARSEOPT },
 	{ "init", cmd_init_db },
meson.build +1 -0
index a5a4e99b25..3a1d12caa4 100644
@@ -610,6 +610,7 @@ builtin_sources = [
   'builtin/grep.c',
   'builtin/hash-object.c',
   'builtin/help.c',
+  'builtin/history.c',
   'builtin/hook.c',
   'builtin/index-pack.c',
   'builtin/init-db.c',
t/meson.build +1 -0
index 459c52a489..73006b095a 100644
@@ -387,6 +387,7 @@ integration_tests = [
   't3436-rebase-more-options.sh',
   't3437-rebase-fixup-options.sh',
   't3438-rebase-broken-files.sh',
+  't3450-history.sh',
   't3500-cherry.sh',
   't3501-revert-cherry-pick.sh',
   't3502-cherry-pick-merge.sh',
t/t3450-history.sh new file +17 -0
new file mode 100755
index 0000000000..417c343d43
@@ -0,0 +1,17 @@
+#!/bin/sh
+
+test_description='tests for git-history command'
+
+. ./test-lib.sh
+
+test_expect_success 'does nothing without any arguments' '
+	git history >out 2>&1 &&
+	test_must_be_empty out
+'
+
+test_expect_success 'raises an error with unknown argument' '
+	test_must_fail git history garbage 2>err &&
+	test_grep "unrecognized argument: garbage" err
+'
+
+test_done
Signature · 1 line
2.52.0.542.g9473a8513b.dirty
#314 lore raw

Re: [PATCH v9 6/7] builtin: add new "history" command

Quoted 90 lines · Patrick Steinhardt

When rewriting history via git-rebase(1) there are a few very common use cases:

- The ordering of two commits should be reversed.

- A commit should be split up into two commits.

- A commit should be dropped from the history completely.

- Multiple commits should be squashed into one.

- Editing an existing commit that is not the tip of the current branch.

While these operations are all doable, it often feels needlessly kludgey to do so by doing an interactive rebase, using the editor to say what one wants, and then perform the actions. Also, some operations like splitting up a commit into two are way more involved than that and require a whole series of commands.

Rebases also do not update dependent branches. The use of stacked branches has grown quite common with competing version control systems like Jujutsu though, so it clearly is a need that users have. While rebases _can_ serve this use case if one always works on the latest stacked branch, it is somewhat awkward and very easy to get wrong.

Add a new "history" command to plug these gaps. This command will have several different subcommands to imperatively rewrite history for common use cases like the above.

---
 .gitignore                     |  1 +
 Documentation/git-history.adoc | 56 ++++++++++++++++++++++++++++++++++++++++++
 Documentation/meson.build      |  1 +
 Makefile                       |  1 +
 builtin.h                      |  1 +
 builtin/history.c              | 22 +++++++++++++++++
 command-list.txt               |  1 +
 git.c                          |  1 +
 meson.build                    |  1 +
 t/meson.build                  |  1 +
 t/t3450-history.sh             | 17 +++++++++++++
 11 files changed, 103 insertions(+)
.gitignore +1 -0
index 78a45cb5be..24635cf2d6 100644
@@ -79,6 +79,7 @@
 /git-grep
 /git-hash-object
 /git-help
+/git-history
 /git-hook
 /git-http-backend
 /git-http-fetch
Documentation/git-history.adoc new file +26 -0
new file mode 100644
index 0000000000..5a9d931efc
@@ -0,0 +1,56 @@
+git-history(1)
+==============
+
+NAME
+----
+git-history - EXPERIMENTAL: Rewrite history
+
+SYNOPSIS
+--------
+[synopsis]
+git history [<options>]
+
+DESCRIPTION
+-----------
+
+Rewrite history by rearranging or modifying specific commits in the
+history.
+
+THIS COMMAND IS EXPERIMENTAL. THE BEHAVIOR MAY CHANGE.
+
+This command is related to linkgit:git-rebase[1] in that both commands can be
+used to rewrite history. There are a couple of major differences though:
+
+* linkgit:git-history[1] can work in a bare repository as it does not need to
+  touch either the index or the worktree.
+* linkgit:git-history[1] does not execute any linkgit:githooks[5] at the

Documentation/git-history.adoc line 36

Quoted 10 lines
Documentation/git-history.adoc new file +10 -0
+  current point in time. This may change in the future.
+* linkgit:git-history[1] by default updates all branches that are descendants
+  of the original commit to point to the rewritten commit.
+
+Overall, linkgit:git-history[1] aims to provide a more opinionated way to modify
+your commit history that is simpler to use compared to linkgit:git-rebase[1] in
+general.
+
+If you want to reapply a range of commits onto a different base, or interactive
+rebases if you want to edit a range of commits.

"If ..." with no "then ..." ? This sentence isn't complete.

Quoted 5 lines
Documentation/git-history.adoc new file +5 -0
+LIMITATIONS
+-----------
+
+This command does not (yet) work with histories that contain merges. You
+should use linkgit:git-rebase[1] with the `--rebase-merges` flag instead.

Documentation/git-history.adoc line 52

Quoted 10 lines
Documentation/git-history.adoc new file +10 -0
+
+Furthermore, the command does not support operations that can result in merge
+conflicts. This limitation is by design as history rewrites are not intended to
+be stateful operations. The limitation can be lifted once (if) Git learns about
+first-class conflicts.
+
+COMMANDS
+--------
+
+Several commands are available to rewrite history in different ways:

Um, what are they?

Quoted 56 lines
Documentation/git-history.adoc new file +4 -0
+
+GIT
+---
+Part of the linkgit:git[1] suite
Documentation/meson.build +1 -0
index f02dbc20cb..fd2e8cc02d 100644
@@ -64,6 +64,7 @@ manpages = {
   'git-gui.adoc' : 1,
   'git-hash-object.adoc' : 1,
   'git-help.adoc' : 1,
+  'git-history.adoc' : 1,
   'git-hook.adoc' : 1,
   'git-http-backend.adoc' : 1,
   'git-http-fetch.adoc' : 1,
Makefile +1 -0
index 1c64a5d2ae..c0569ed8e4 100644
@@ -1418,6 +1418,7 @@ BUILTIN_OBJS += builtin/get-tar-commit-id.o
 BUILTIN_OBJS += builtin/grep.o
 BUILTIN_OBJS += builtin/hash-object.o
 BUILTIN_OBJS += builtin/help.o
+BUILTIN_OBJS += builtin/history.o
 BUILTIN_OBJS += builtin/hook.o
 BUILTIN_OBJS += builtin/index-pack.o
 BUILTIN_OBJS += builtin/init-db.o
builtin.h +1 -0
index 1b35565fbd..93c91d07d4 100644
@@ -172,6 +172,7 @@ int cmd_get_tar_commit_id(int argc, const char **argv, const char *prefix, struc
 int cmd_grep(int argc, const char **argv, const char *prefix, struct repository *repo);
 int cmd_hash_object(int argc, const char **argv, const char *prefix, struct repository *repo);
 int cmd_help(int argc, const char **argv, const char *prefix, struct repository *repo);
+int cmd_history(int argc, const char **argv, const char *prefix, struct repository *repo);
 int cmd_hook(int argc, const char **argv, const char *prefix, struct repository *repo);
 int cmd_index_pack(int argc, const char **argv, const char *prefix, struct repository *repo);
 int cmd_init_db(int argc, const char **argv, const char *prefix, struct repository *repo);
builtin/history.c new file +10 -0
new file mode 100644
index 0000000000..f6fe32610b
@@ -0,0 +1,22 @@
+#include "builtin.h"
+#include "gettext.h"
+#include "parse-options.h"
+
+int cmd_history(int argc,
+               const char **argv,
+               const char *prefix,
+               struct repository *repo UNUSED)
+{
+       const char * const usage[] = {

builtin/history.c line 20

Quoted 10 lines
builtin/history.c new file +10 -0
+               N_("git history [<options>]"),
+               NULL,
+       };
+       struct option options[] = {
+               OPT_END(),
+       };
+
+       argc = parse_options(argc, argv, prefix, options, usage, 0);
+       if (argc)
+               usagef("unrecognized argument: %s", argv[0]);

Oh, the manual is just a placeholder that you'll extend later? That makes sense, but it would be less confusing if it started out with "No subcommands are yet supported, but will be added later", with that sentence removed in the next commit when you add a subcommand.

Quoted 76 lines
builtin/history.c new file +2 -0
+       return 0;
+}
command-list.txt +1 -0
index accd3d0c4b..f9005cf459 100644
@@ -115,6 +115,7 @@ git-grep                                mainporcelain           info
 git-gui                                 mainporcelain
 git-hash-object                         plumbingmanipulators
 git-help                                ancillaryinterrogators          complete
+git-history                             mainporcelain           history
 git-hook                                purehelpers
 git-http-backend                        synchingrepositories
 git-http-fetch                          synchelpers
git.c +1 -0
index c5fad56813..744cb6527e 100644
@@ -586,6 +586,7 @@ static struct cmd_struct commands[] = {
        { "grep", cmd_grep, RUN_SETUP_GENTLY },
        { "hash-object", cmd_hash_object },
        { "help", cmd_help },
+       { "history", cmd_history, RUN_SETUP },
        { "hook", cmd_hook, RUN_SETUP },
        { "index-pack", cmd_index_pack, RUN_SETUP_GENTLY | NO_PARSEOPT },
        { "init", cmd_init_db },
meson.build +1 -0
index a5a4e99b25..3a1d12caa4 100644
@@ -610,6 +610,7 @@ builtin_sources = [
   'builtin/grep.c',
   'builtin/hash-object.c',
   'builtin/help.c',
+  'builtin/history.c',
   'builtin/hook.c',
   'builtin/index-pack.c',
   'builtin/init-db.c',
t/meson.build +1 -0
index 459c52a489..73006b095a 100644
@@ -387,6 +387,7 @@ integration_tests = [
   't3436-rebase-more-options.sh',
   't3437-rebase-fixup-options.sh',
   't3438-rebase-broken-files.sh',
+  't3450-history.sh',
   't3500-cherry.sh',
   't3501-revert-cherry-pick.sh',
   't3502-cherry-pick-merge.sh',
t/t3450-history.sh new file +17 -1
new file mode 100755
index 0000000000..417c343d43
@@ -0,0 +1,17 @@
+#!/bin/sh
+
+test_description='tests for git-history command'
+
+. ./test-lib.sh
+
+test_expect_success 'does nothing without any arguments' '
+       git history >out 2>&1 &&
+       test_must_be_empty out
+'
+
+test_expect_success 'raises an error with unknown argument' '
+       test_must_fail git history garbage 2>err &&
+       test_grep "unrecognized argument: garbage" err
+'
+
+test_done
 
--

2.52.0.542.g9473a8513b.dirty

#315 lore raw

Re: [PATCH v9 6/7] builtin: add new "history" command

Quoted 37 lines · Elijah Newren
Quoted 36 lines · Patrick Steinhardt
Documentation/git-history.adoc new file +30 -0
new file mode 100644
index 0000000000..5a9d931efc
@@ -0,0 +1,56 @@
+git-history(1)
+==============
+
+NAME
+----
+git-history - EXPERIMENTAL: Rewrite history
+
+SYNOPSIS
+--------
+[synopsis]
+git history [<options>]
+
+DESCRIPTION
+-----------
+
+Rewrite history by rearranging or modifying specific commits in the
+history.
+
+THIS COMMAND IS EXPERIMENTAL. THE BEHAVIOR MAY CHANGE.
+
+This command is related to linkgit:git-rebase[1] in that both commands can be
+used to rewrite history. There are a couple of major differences though:
+
+* linkgit:git-history[1] can work in a bare repository as it does not need to
+  touch either the index or the worktree.
+* linkgit:git-history[1] does not execute any linkgit:githooks[5] at the
+  current point in time. This may change in the future.
+* linkgit:git-history[1] by default updates all branches that are descendants
+  of the original commit to point to the rewritten commit.
+
Quoted 8 lines

Documentation/git-history.adoc line 36

Quoted 6 lines
Documentation/git-history.adoc new file +6 -0
+Overall, linkgit:git-history[1] aims to provide a more opinionated way to modify
+your commit history that is simpler to use compared to linkgit:git-rebase[1] in
+general.
+
+If you want to reapply a range of commits onto a different base, or interactive
+rebases if you want to edit a range of commits.

"If ..." with no "then ..." ? This sentence isn't complete.

Oh, true. I noticed this error, but only fixed it in the next commit. Will move around.

Quoted 23 lines
Quoted 23 lines
builtin/history.c new file +17 -0
new file mode 100644
index 0000000000..f6fe32610b
@@ -0,0 +1,22 @@
+#include "builtin.h"
+#include "gettext.h"
+#include "parse-options.h"
+
+int cmd_history(int argc,
+               const char **argv,
+               const char *prefix,
+               struct repository *repo UNUSED)
+{
+       const char * const usage[] = {
+               N_("git history [<options>]"),
+               NULL,
+       };
+       struct option options[] = {
+               OPT_END(),
+       };
+
Quoted 8 lines

builtin/history.c line 20

Quoted 3 lines
builtin/history.c new file +3 -0
+       argc = parse_options(argc, argv, prefix, options, usage, 0);
+       if (argc)
+               usagef("unrecognized argument: %s", argv[0]);

Oh, the manual is just a placeholder that you'll extend later? That makes sense, but it would be less confusing if it started out with "No subcommands are yet supported, but will be added later", with that sentence removed in the next commit when you add a subcommand.

Yup. Will change.

Patrick

#316 lore raw

PATCH v9 7/7 builtin/history: implement "reword" subcommand

In reply to Patrick Steinhardt

Implement a new "reword" subcommand for git-history(1). This subcommand is similar to the user performing an interactive rebase with a single commit changed to use the "reword" instruction.

The "reword" subcommand is built on top of the replay subsystem instead of the sequencer. This leads to some major differences compared to git-rebase(1):

- We do not check out the commit that is to be reworded and instead perform the operation in-memory. This has the obvious benefit of being significantly faster compared to git-rebase(1), but even more importantly it allows the user to rewrite history even if there are local changes in the working tree or in the index.

- We do not execute any hooks, even though we leave some room for changing this in the future.

- By default, all local branches that contain the commit will be rewritten. This especially helps with workflows that use stacked branches.

---
 Documentation/git-history.adoc |  23 ++-
 builtin/history.c              | 392 ++++++++++++++++++++++++++++++++++++++++-
 replay.c                       |   5 +-
 t/meson.build                  |   1 +
 t/t3450-history.sh             |   6 +-
 t/t3451-history-reword.sh      | 344 ++++++++++++++++++++++++++++++++++++
 6 files changed, 758 insertions(+), 13 deletions(-)
Documentation/git-history.adoc +20 -3
index 5a9d931efc..4eea317e5c 100644
@@ -8,7 +8,7 @@ git-history - EXPERIMENTAL: Rewrite history
 SYNOPSIS
 --------
 [synopsis]
-git history [<options>]
+git history reword <commit> [--ref-action=(branches|head|print)]
 
 DESCRIPTION
 -----------
@@ -32,8 +32,9 @@ Overall, linkgit:git-history[1] aims to provide a more opinionated way to modify
 your commit history that is simpler to use compared to linkgit:git-rebase[1] in
 general.
 
-If you want to reapply a range of commits onto a different base, or interactive
-rebases if you want to edit a range of commits.
+Use linkgit:git-rebase[1] if you want to reapply a range of commits onto a
+different base, or interactive rebases if you want to edit a range of commits
+at once.
 
 LIMITATIONS
 -----------
@@ -51,6 +52,22 @@ COMMANDS
 
 Several commands are available to rewrite history in different ways:
 
+`reword <commit>`::
+	Rewrite the commit message of the specified commit. All the other
+	details of this commit remain unchanged. This command will spawn an
+	editor with the current message of that commit.
+
+OPTIONS
+-------
+
+`--ref-action=(branches|head|print)`::
+	Control which references will be updated by the command, if any. With
+	`branches`, all local branches that point to commits which are
+	decendants of the original commit will be rewritten. With `head`, only
+	the current `HEAD` reference will be rewritten. With `print`, all
+	updates as they would be performed with `branches` are printed in a
+	format that can be consumed by linkgit:git-update-ref[1].
+
 GIT
 ---
 Part of the linkgit:git[1] suite
builtin/history.c +387 -5

409 lines not on this page · raw message

replay.c +3 -2
index 20560e792b..74e45ed27a 100644
@@ -266,7 +266,9 @@ int replay_revisions(struct repository *repo, struct rev_info *revs,
 	struct commit *commit;
 	struct commit *onto = NULL;
 	struct merge_options merge_opt;
-	struct merge_result result;
+	struct merge_result result = {
+		.clean = 1,
+	};
 	char *advance;
 	int ret;
 
@@ -282,7 +284,6 @@ int replay_revisions(struct repository *repo, struct rev_info *revs,
 	}
 
 	init_basic_merge_options(&merge_opt, repo);
-	memset(&result, 0, sizeof(result));
 	merge_opt.show_rename_progress = 0;
 	last_commit = onto;
 	replayed_commits = kh_init_oid_map();
t/meson.build +1 -0
index 73006b095a..c9f92450dc 100644
@@ -388,6 +388,7 @@ integration_tests = [
   't3437-rebase-fixup-options.sh',
   't3438-rebase-broken-files.sh',
   't3450-history.sh',
+  't3451-history-reword.sh',
   't3500-cherry.sh',
   't3501-revert-cherry-pick.sh',
   't3502-cherry-pick-merge.sh',
t/t3450-history.sh +3 -3
index 417c343d43..f513463b92 100755
@@ -5,13 +5,13 @@ test_description='tests for git-history command'
 . ./test-lib.sh
 
 test_expect_success 'does nothing without any arguments' '
-	git history >out 2>&1 &&
-	test_must_be_empty out
+	test_must_fail git history 2>err &&
+	test_grep "need a subcommand" err
 '
 
 test_expect_success 'raises an error with unknown argument' '
 	test_must_fail git history garbage 2>err &&
-	test_grep "unrecognized argument: garbage" err
+	test_grep "unknown subcommand: .garbage." err
 '
 
 test_done
t/t3451-history-reword.sh new file +344 -0

344 lines not on this page · raw message

Signature · 1 line
2.52.0.542.g9473a8513b.dirty
#317 lore raw
In reply to Patrick Steinhardt
Quoted 7 lines · Patrick Steinhardt

Changes in v9:
- Rename struct replay_ref_updates to struct replay_result to make
its semantics less focussed on ref updates, only.
- Clarify and fix return codes of git-replay(1) so that we return 1 on
conflict, 128 on an error and 0 on success.
- The usual small improvements to commit messages.
- Link to v8: https://lore.kernel.org/r/[email protected]

I read through this series in detail; it's forming into shape nicely. I think there's still a number of small implementation things to fix up (see my comments on the individual patches), but the design looks good to me now. I suspect we'll be ready to merge before long.

Thanks for your patience and hard work on this!

#318 lore raw
Quoted 9 lines · Elijah Newren
Quoted 7 lines · Patrick Steinhardt

Changes in v9:
- Rename struct replay_ref_updates to struct replay_result to make
its semantics less focussed on ref updates, only.
- Clarify and fix return codes of git-replay(1) so that we return 1 on
conflict, 128 on an error and 0 on success.
- The usual small improvements to commit messages.
- Link to v8: https://lore.kernel.org/r/[email protected]

Quoted 4 lines

I read through this series in detail; it's forming into shape nicely. I think there's still a number of small implementation things to fix up (see my comments on the individual patches), but the design looks good to me now. I suspect we'll be ready to merge before long.

I don't think this should be merged until we have clear and feasible plans for future subcommands that will cause conflicts, to avoid painting ourselves into a corner, like when we couldn't change the not well thought out details of 'git switch/restore' anymore.

#319 lore raw
Quoted 15 lines · SZEDER Gábor
Quoted 9 lines · Elijah Newren
Quoted 7 lines · Patrick Steinhardt

Changes in v9:
- Rename struct replay_ref_updates to struct replay_result to make
its semantics less focussed on ref updates, only.
- Clarify and fix return codes of git-replay(1) so that we return 1 on
conflict, 128 on an error and 0 on success.
- The usual small improvements to commit messages.
- Link to v8: https://lore.kernel.org/r/[email protected]

Quoted 4 lines

I read through this series in detail; it's forming into shape nicely. I think there's still a number of small implementation things to fix up (see my comments on the individual patches), but the design looks good to me now. I suspect we'll be ready to merge before long.

Quoted 4 lines

I don't think this should be merged until we have clear and feasible plans for future subcommands that will cause conflicts, to avoid painting ourselves into a corner, like when we couldn't change the not well thought out details of 'git switch/restore' anymore.

I agree that we need to think a bit about how we'll handle conflicts eventually. But I don't agree that this means we cannot already merge this series for subcommands that _cannot_ have conflicts as I don't really see how design decisions around handling conflicts would have an influence on subcommands that never have any conflicts in the first place.

The intent of this command is that it should allow users to easily handle certain common operations, without them having to worry about the underpinnings. So even if we eventually figure out that the replay subsystem is not a good fit for e.g. a potential git history edit command I don't think that this means that the whole status quo of git history reword would be impacted. And even if we eventuall _do_ decide to switch back to for example the sequencer subsystem I wouldn't expect that to impact the overall design of git history reword either.

So yes, I think we should have a discussion around how we can:

- Handle conflicts in replay-based commands in general.

- Support stacked branches workflows with conflicting commits.

From my point of view this leads into the direction of first-class conflicts in Git, and I think Elijah also leans into that direction. But it feels like a separate discussion to be had that is independent from the current proposed subcommands.

Also, with the new semantics that we have aligned on with dependent branches being rewritten I also think that we'll want to get the inital infrastructure out there to facilitate user feedback. Such feedback can also help us align on a better design for git-history(1) going forward.

Thanks!

Patrick

#320 lore raw

cover Some

In reply to Patrick Steinhardt

I've been waiting for the history series to consolidate before upstream some local GitHub changes to replay and adding some others of my own.

So, I figured sending some of my suggestions from my reviews as a "SQUASH ME" patch that Patrick could split up and squash into his series might be helpful.

Plus, I noticed a bug (pre-dating his series) with handling of detached heads in replay that has propagated with his history stuff, so I added a second patch to fix that bug in both replay and history..

Elijah Newren (2):
SQUASH ME: Fixups
history: fix detached HEAD handling

 Documentation/git-history.adoc |  2 +-
 builtin/history.c              | 31 ++++++++++++----------
 builtin/replay.c               | 10 ++------
 replay.c                       | 28 +++++++++++++-------
 replay.h                       | 21 +--------------
 t/t3451-history-reword.sh      | 47 ++++++++++++++++++++++++++++++++++
 6 files changed, 87 insertions(+), 52 deletions(-)
Signature · 1 line
2.52.0.410.g227cdbe8e36
#321 lore raw

[PATCH v9 8/7] SQUASH ME: Fixups

This includes several fixes I highlighted in my review and needs to be split up and squashed into the relevant previous patches.

---
 Documentation/git-history.adoc |  2 +-
 builtin/history.c              | 16 ++++------------
 builtin/replay.c               | 10 ++--------
 replay.c                       | 10 ++++------
 replay.h                       | 21 +--------------------
 5 files changed, 12 insertions(+), 47 deletions(-)
Documentation/git-history.adoc +1 -1
index 4eea317e5cb..457a1314a51 100644
@@ -63,7 +63,7 @@ OPTIONS
 `--ref-action=(branches|head|print)`::
 	Control which references will be updated by the command, if any. With
 	`branches`, all local branches that point to commits which are
-	decendants of the original commit will be rewritten. With `head`, only
+	descendants of the original commit will be rewritten. With `head`, only
 	the current `HEAD` reference will be rewritten. With `print`, all
 	updates as they would be performed with `branches` are printed in a
 	format that can be consumed by linkgit:git-update-ref[1].
builtin/history.c +4 -12
index 28db6fc5b9e..60c5b5c5c76 100644
@@ -178,9 +178,7 @@ static int handle_reference_updates(enum ref_action action,
 {
 	const struct name_decoration *decoration;
 	struct replay_revisions_options opts = { 0 };
-	struct replay_result result = {
-		.final_oid = rewritten->object.oid,
-	};
+	struct replay_result result = { 0 };
 	struct ref_transaction *transaction = NULL;
 	struct strvec args = STRVEC_INIT;
 	struct strbuf err = STRBUF_INIT;
@@ -233,7 +231,7 @@ static int handle_reference_updates(enum ref_action action,
 			goto out;
 		}
 
-		strvec_push(&args, oid_to_hex(&head->object.oid));
+		strvec_push(&args, "HEAD");
 	} else {
 		strvec_push(&args, "--branches");
 	}
@@ -244,13 +242,14 @@ static int handle_reference_updates(enum ref_action action,
 
 	opts.onto = oid_to_hex_r(hex, &rewritten->object.oid);
 
-	ret = replay_revisions(repo, &revs, &opts, &result);
+	ret = replay_revisions(&revs, &opts, &result);
 	if (ret)
 		goto out;
 
 	switch (action) {
 	case REF_ACTION_DEFAULT:
 	case REF_ACTION_BRANCHES:
+	case REF_ACTION_HEAD:
 		transaction = ref_store_transaction_begin(get_main_ref_store(repo), 0, &err);
 		if (!transaction) {
 			ret = error(_("failed to begin ref transaction: %s"), err.buf);
@@ -300,13 +299,6 @@ static int handle_reference_updates(enum ref_action action,
 		}
 
 		break;
-	case REF_ACTION_HEAD:
-		ret = refs_update_ref(get_main_ref_store(repo), reflog_msg, "HEAD",
-				      &result.final_oid, &head->object.oid, 0,
-				      UPDATE_REFS_MSG_ON_ERR);
-		if (ret)
-			goto out;
-		break;
 	case REF_ACTION_PRINT:
 		for (size_t i = 0; i < result.updates_nr; i++)
 			printf("update %s %s %s\n",
builtin/replay.c +2 -8
index da8b7202f6a..f66e1a1fcd3 100644
@@ -167,7 +167,7 @@ int cmd_replay(int argc,
 		revs.simplify_history = 0;
 	}
 
-	ret = replay_revisions(repo, &revs, &opts, &result);
+	ret = replay_revisions(&revs, &opts, &result);
 	if (ret)
 		goto cleanup;
 
@@ -220,11 +220,5 @@ int cmd_replay(int argc,
 	strbuf_release(&reflog_msg);
 	release_revisions(&revs);
 
-	if (ret) {
-		if (result.merge_conflict)
-			return 1;
-		return 128;
-	}
-
-	return 0;
+	return ret;
 }
replay.c +4 -6
index 74e45ed27a2..ea300e3c36c 100644
@@ -5,11 +5,11 @@
 #include "hex.h"
 #include "merge-ort.h"
 #include "object-name.h"
-#include "oidset.h"
 #include "parse-options.h"
 #include "refs.h"
 #include "replay.h"
 #include "revision.h"
+#include "strmap.h"
 #include "tree.h"
 
 static const char *short_commit_name(struct repository *repo,
@@ -256,7 +256,7 @@ static void replay_result_queue_update(struct replay_result *result,
 	result->updates_nr++;
 }
 
-int replay_revisions(struct repository *repo, struct rev_info *revs,
+int replay_revisions(struct rev_info *revs,
 		     struct replay_revisions_options *opts,
 		     struct replay_result *out)
 {
@@ -265,6 +265,7 @@ int replay_revisions(struct repository *repo, struct rev_info *revs,
 	struct commit *last_commit = NULL;
 	struct commit *commit;
 	struct commit *onto = NULL;
+	struct repository *repo = revs->repo;
 	struct merge_options merge_opt;
 	struct merge_result result = {
 		.clean = 1,
@@ -328,8 +329,7 @@ int replay_revisions(struct repository *repo, struct rev_info *revs,
 	}
 
 	if (!result.clean) {
-		out->merge_conflict = true;
-		ret = -1;
+		ret = 1;
 		goto out;
 	}
 
@@ -339,8 +339,6 @@ int replay_revisions(struct repository *repo, struct rev_info *revs,
 					   &onto->object.oid,
 					   &last_commit->object.oid);
 
-	out->final_oid = last_commit->object.oid;
-
 	ret = 0;
 
 out:
replay.h +1 -20
index f8f9889112e..9b31c85dd9b 100644
@@ -43,25 +43,6 @@ struct replay_result {
 		struct object_id new_oid;
 	} *updates;
 	size_t updates_nr, updates_alloc;
-
-	/* Set to true in case the replay failed with a merge conflict. */
-	bool merge_conflict;
-
-	/*
-	 * The final object ID that was rewritten. Note that this field has
-	 * somewhat special semantics and may or may not be what you want:
-	 *
-	 *   - If no commits were rewritten it will remain uninitialized.
-	 *
-	 *   - If a thicket of branches is rewritten it is undefined in which
-	 *     order those branches will be rewritten, and thus the final object
-	 *     ID may point to a different commit than you'd expect.
-	 *
-	 * That being said, this field can still be useful when you know that
-	 * you only replay a single strand of commits. In that case, the final
-	 * commit will point to the tip of the rewritten strand of commits.
-	 */
-	struct object_id final_oid;
 };
 
 void replay_result_release(struct replay_result *result);
@@ -73,7 +54,7 @@ void replay_result_release(struct replay_result *result);
  *
  * Returns 0 on success, a negative error code otherwise.
  */
-int replay_revisions(struct repository *repo, struct rev_info *revs,
+int replay_revisions(struct rev_info *revs,
 		     struct replay_revisions_options *opts,
 		     struct replay_result *out);
 
Signature · 1 line
2.52.0.410.g227cdbe8e36
#322 lore raw

[PATCH v9 9/7] history: fix detached HEAD handling

In reply to Elijah Newren

The default behavior for history is to work on all local branches. When HEAD is detached, it should be treated like a local branch as well. The primary fix for this is just to make sure that in addition to passing --branches to the revision machinery that we pass HEAD as well.

However, that doesn't quite do the trick, because we also process the "decorations" that point at commits that we have processed, and we do this in two places -- in replay_revisions() as we replay commits, and in handle_reference_updates() when there are no commits to replay because the commit at the tip of the revision range was the one edited. In both cases, we previously keyed off of DECORATION_REF_LOCAL to make sure we only looked at local branches. Now, we need to also pay attention to DECORATION_REF_HEAD. However, in order to avoid doing two updates to the same branch (which will the ref transaction framework would throw an error on), we need to only pay attention to DECORATION_REF_HEAD when we have a detached HEAD.

---
 builtin/history.c         | 15 +++++++++++--
 replay.c                  | 18 ++++++++++++---
 t/t3451-history-reword.sh | 47 +++++++++++++++++++++++++++++++++++++++
 3 files changed, 75 insertions(+), 5 deletions(-)
builtin/history.c +13 -2
index 60c5b5c5c76..dd0df89c94e 100644
@@ -183,10 +183,18 @@ static int handle_reference_updates(enum ref_action action,
 	struct strvec args = STRVEC_INIT;
 	struct strbuf err = STRBUF_INIT;
 	struct commit *head = NULL;
+	char *head_ref = NULL;
+	bool detached_head = false;
 	struct rev_info revs;
 	char hex[GIT_MAX_HEXSZ + 1];
 	int ret;
 
+	head_ref = refs_resolve_refdup(get_main_ref_store(repo), "HEAD",
+				       RESOLVE_REF_READING, NULL, NULL);
+	if (!strcmp(head_ref, "HEAD"))
+		detached_head = true;
+	free(head_ref);
+
 	repo_init_revisions(repo, &revs, NULL);
 	strvec_push(&args, "ignored");
 	strvec_push(&args, "--reverse");
@@ -234,6 +242,7 @@ static int handle_reference_updates(enum ref_action action,
 		strvec_push(&args, "HEAD");
 	} else {
 		strvec_push(&args, "--branches");
+		strvec_push(&args, "HEAD");
 	}
 
 	setup_revisions_from_strvec(&args, &revs, NULL);
@@ -278,9 +287,11 @@ static int handle_reference_updates(enum ref_action action,
 		     decoration;
 		     decoration = decoration->next)
 		{
-			if (decoration->type != DECORATION_REF_LOCAL)
+			if ((decoration->type != DECORATION_REF_HEAD ||
+			     (action != REF_ACTION_HEAD && !detached_head)) &&
+			    (decoration->type != DECORATION_REF_LOCAL ||
+			     action == REF_ACTION_HEAD))
 				continue;
-
 			ret = ref_transaction_update(transaction,
 						     decoration->name,
 						     &rewritten->object.oid,
replay.c +15 -3
index ea300e3c36c..7c98b1d1044 100644
@@ -151,11 +151,20 @@ static void get_ref_information(struct repository *repo,
 static void set_up_replay_mode(struct repository *repo,
 			       struct rev_cmdline_info *cmd_info,
 			       const char *onto_name,
+			       bool *detached_head,
 			       char **advance_name,
 			       struct commit **onto,
 			       struct strset **update_refs)
 {
 	struct ref_info rinfo;
+	char *head_ref;
+
+	*detached_head = false;
+	head_ref = refs_resolve_refdup(get_main_ref_store(repo), "HEAD",
+				       RESOLVE_REF_READING, NULL, NULL);
+	if (!strcmp(head_ref, "HEAD"))
+		*detached_head = true;
+	free(head_ref);
 
 	get_ref_information(repo, cmd_info, &rinfo);
 	if (!rinfo.positive_refexprs)
@@ -271,11 +280,12 @@ int replay_revisions(struct rev_info *revs,
 		.clean = 1,
 	};
 	char *advance;
+	bool detached_head;
 	int ret;
 
 	advance = xstrdup_or_null(opts->advance);
-	set_up_replay_mode(repo, &revs->cmdline, opts->onto, &advance,
-			   &onto, &update_refs);
+	set_up_replay_mode(repo, &revs->cmdline, opts->onto,
+			   &detached_head, &advance, &onto, &update_refs);
 
 	/* FIXME: Should allow replaying commits with the first as a root commit */
 
@@ -317,7 +327,9 @@ int replay_revisions(struct rev_info *revs,
 		if (!decoration)
 			continue;
 		while (decoration) {
-			if (decoration->type == DECORATION_REF_LOCAL &&
+			if ((decoration->type == DECORATION_REF_LOCAL ||
+			     (decoration->type == DECORATION_REF_HEAD &&
+			      detached_head)) &&
 			    (opts->contained || strset_contains(update_refs,
 								decoration->name))) {
 				replay_result_queue_update(out, decoration->name,
t/t3451-history-reword.sh +47 -0

53 lines not on this page · raw message

Signature · 1 line
2.52.0.410.g227cdbe8e36
#323 lore raw

Re: [PATCH 0/2] Some

In reply to Elijah Newren

The subject should have been "Some fixes for ps/history and replay". Oops.

Quoted 28 lines · Elijah Newren

I've been waiting for the history series to consolidate before upstream some local GitHub changes to replay and adding some others of my own.

So, I figured sending some of my suggestions from my reviews as a "SQUASH ME" patch that Patrick could split up and squash into his series might be helpful.

Plus, I noticed a bug (pre-dating his series) with handling of detached heads in replay that has propagated with his history stuff, so I added a second patch to fix that bug in both replay and history..

Elijah Newren (2):
SQUASH ME: Fixups
history: fix detached HEAD handling

 Documentation/git-history.adoc |  2 +-
 builtin/history.c              | 31 ++++++++++++----------
 builtin/replay.c               | 10 ++------
 replay.c                       | 28 +++++++++++++-------
 replay.h                       | 21 +--------------
 t/t3451-history-reword.sh      | 47 ++++++++++++++++++++++++++++++++++
 6 files changed, 87 insertions(+), 52 deletions(-)

--
2.52.0.410.g227cdbe8e36

#324 lore raw

Re: [PATCH 0/2] Some

In reply to Elijah Newren
Quoted 11 lines · Elijah Newren

I've been waiting for the history series to consolidate before upstream some local GitHub changes to replay and adding some others of my own.

So, I figured sending some of my suggestions from my reviews as a "SQUASH ME" patch that Patrick could split up and squash into his series might be helpful.

Plus, I noticed a bug (pre-dating his series) with handling of detached heads in replay that has propagated with his history stuff, so I added a second patch to fix that bug in both replay and history..

Perfect, I'll work these patches into my series. Thanks!

Patrick

#325 lore raw

v10 cover Introduce git-history(1) command for easy history editing

In reply to Patrick Steinhardt

Hi,

over recent months I've been playing around with Jujutsu quite frequently. While I still prefer using Git, there's been a couple features in it that I really like and that I'd like to have in Git, as well.

A copule of these features relate to history editing. Most importantly, I really dig the following commands:

- jj-abandon(1) to drop a specific commit from your history.

- jj-absorb(1) to take some changes and automatically apply them to commits in your history that last modified the respective hunks.

- jj-split(1) to split a commit into two.

- jj-new(1) to insert a new commit after or before a specific other commit.

Not all of these commands can be ported directly into Git. jj-new(1) for example doesn't really make a ton of sense for us, I'd claim. But some of these commands _do_ make sense.

This patch series is a starting point for such a command. For now, it only implements rewording of commits. I'll continue introducing new commands once this patch series has been merged though.

Changes in v10:
- Split out changes that make replay_revisions() handle empty revision ranges properly.
- Drop redundant struct repository parameter in

    `replay_revisions()`.

- Move around die_for_incompatible_opt2().
- Fix up some of the headers in "replay.c".
- Split out the changes that make replay_revisions() handle empty
revision ranges properly.
- Create a separate commit that fixes updating detached HEAD.
- Strip "encoding" header as we're reencoding commit messages.
- Merge the logic to update refs in in REF_ACTION_HEAD and REF_ACTION_BRANCHES modes.
- Link to v9: https://lore.kernel.org/r/[email protected]

Changes in v9:
- Rename struct replay_ref_updates to struct replay_result to make
its semantics less focussed on ref updates, only.
- Clarify and fix return codes of git-replay(1) so that we return 1 on
conflict, 128 on an error and 0 on success.
- The usual small improvements to commit messages.
- Link to v8: https://lore.kernel.org/r/[email protected]

Changes in v8:
- The series is now built on top of e0bfec3dfc (The 15th batch,
2026-01-06) with kh/replay-invalid-onto-advance at 56b77a687e
(t3650: add more regression tests for failure conditions,
2026-01-05) merged into it. The latter is expected to hit 'next'
soonish.
- Another biggish revamp to build almost completely on top of the
git-replay(1) logic.
- We now advance all branches descending from the rewritten commit by
default.
- I've dropped the patches introducing git history split and will
send this as a follow-up patch series once this once has been
merged. This was done to focus attention on the underlying mechanics
as much as possible (and to keep my own sanity with the frequent
revamps).
- Link to v7: https://lore.kernel.org/r/[email protected]

Changes in v7:
- I've rebased the patch series on top of f0ef5b6d9b (The fifth batch,

    2025-11-30) with pw/replay-exclude-gpgsig-fix at 9f3a115087 (replay:
    do not copy "gpgsign-sha256" header, 2025-11-26) merged into it to
    fix some conflicts.

- I refactored a bunch of code to be shared between split and reword.
- I am now using "--ancestry-path" and "--reverse" to enumerate
commits.
- git history split now asks for commit messages for both commits.
- git history split no longer allows the user to edit hunks so that
conflicts become impossible. This may be reintroduced at a later
point in time.
- A bunch of test improvements.
- Several commit message and documentation improvements.
- Link to v6: https://lore.kernel.org/r/[email protected]

Changes in v6:
- I've rebased the patch series again to pull in the latest updates from sa/replay-atomic-ref-updates and fix conflicts. It is now based on 4e98b730f1 (The twenty-fourth batch, 2025-10-24) with ab661bb1bb (replay: add replay.refAction config option, 2025-10-23) merged into it.
- I've dropped the "-m" options for now, so commit messages are always asked for via the editor. These can be introduced in a subsequent patch series once discussion around them has settled.
- We don't use the merge machinery anymore to pick the commits.
- Drop the commit to parse commits in the replay machinery. It didn't seem to be necessary in v5 anymore, and now that we don't use the merge machinery at all we don't ever take that code path in the first place.
- Link to v5:

    https://lore.kernel.org/r/[email protected]

Changes in v5:
- I've changed the patch series to be based on top of 133d151831 (The twenty-first batch, 2025-10-20) with sa/replay-atomic-ref-updates at a1c22e627e (SQAUASH??? t0450 band-aid, 2025-10-14) merged into it.
This is one the one hand to fix a conflict, but also to get some of
the CI updates to make GitLab CI work again.
- Some slight commit message improvements.
- Deduplicate subcommand usage strings by using defines.
- Fix the desendancy checks to properly verify that HEAD is a
descendant of the commit to be rewritten. Also add some tests for
this.
- Fix the hint that mentions that lines starting with the comment
character will be tripped after having written the commit message.
- Move an include to the correct commit.
- Link to v4: https://lore.kernel.org/r/[email protected]

Changes in v4:
- I've rebuilt the patch series. It is now based on 821f583da6 (The
thirteenth batcn, 2025-09-29) with sa/replay-atomic-ref-updates
at 665c66a743 (replay: make atomic ref updates the default behavior, 2025-09-27) merged into it. This should fix all conflicts with seen.
- I've reworked this patch series to use the same infra as
git-replay(1), as discussed during the Contributor's Summit.
- I've slimmed down the patch series to only tackle those commands
that cannot result in a conflict to keep it simple. I also learned
that Elijah has been working on a "git replay edit" command, so I
dropped that command so that we can instead use his version.
- During the Contributor's Summit we have agreed that for now, we
won't care about hook execution just yet. This may be backfilled at
a later point in time.
- I dropped "commit.verbose" handling for now, as my understanding of
it was wrong at first. This is something we should backfill.
- Link to v3: https://lore.kernel.org/r/[email protected]

Changes in v3:
- Add logic to drive the "post-rewrite" hook and add tests to verify
that all hooks are executed as expected.
- Deduplicate logic to turn a replay action into a todo command.
- Move the addition of tests for the top-level git-history(1) command
to the correct commit.
- Some smaller commit message fixes.
- Honor "commit.verbose".
- Fix copy-paste error with an error message.
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- Add a new "reword" subcommand.
- List git-history(1) in "command-list.txt".
- Add some missing error handling.
- Simplify calling convention of apply_commits() to handle root
commits internally instead of requiring every caller to do so.
- Add tests to verify that git-history(1) refuses to work with changes
in the worktree or index.
- Mark git-history(1) as experimental.
- Introduce commands to manage interrupted history edits.
- A bunch of improvements to the manpage.
- Link to v1: https://lore.kernel.org/r/[email protected]

Thanks!

Patrick

---
Patrick Steinhardt (8):
builtin/replay: extract core logic to replay revisions builtin/replay: move core logic into "libgit.a"
replay: small set of cleanups
replay: support empty commit ranges
replay: support updating detached HEAD
wt-status: provide function to expose status for trees
builtin: add new "history" command builtin/history: implement "reword" subcommand

 .gitignore                     |   1 +
 Documentation/git-history.adoc |  73 +++++++
 Documentation/meson.build      |   1 +
 Makefile                       |   2 +
 builtin.h                      |   1 +
 builtin/history.c              | 427 +++++++++++++++++++++++++++++++++++++++++
 builtin/replay.c               | 382 ++++--------------------------------
 command-list.txt               |   1 +
 git.c                          |   1 +
 meson.build                    |   2 +
 replay.c                       | 372 +++++++++++++++++++++++++++++++++++
 replay.h                       |  64 ++++++
 t/meson.build                  |   2 +
 t/t3450-history.sh             |  17 ++
 t/t3451-history-reword.sh      | 391 +++++++++++++++++++++++++++++++++++++
 t/t3650-replay-basics.sh       |   9 +
 wt-status.c                    |  24 +++
 wt-status.h                    |   9 +
 18 files changed, 1434 insertions(+), 345 deletions(-)

Range-diff versus v9:

1: 0cae2364ee ! 1: 99b47e1af2 builtin/replay: extract core logic to replay revisions

    @@ Commit message
         Signed-off-by: Patrick Steinhardt <[email protected]>
     
      ## builtin/replay.c ##
    -@@ builtin/replay.c: static enum ref_action_mode get_ref_action_mode(struct repository *repo, const c
    - 	return REF_ACTION_UPDATE;
    +@@ builtin/replay.c: static void set_up_replay_mode(struct repository *repo,
    + 	if (!rinfo.positive_refexprs)
    + 		die(_("need some commits to replay"));
    + 
    +-	die_for_incompatible_opt2(!!onto_name, "--onto",
    +-				  !!*advance_name, "--advance");
    ++	if (!(!!onto_name ^ !!*advance_name))
    ++		BUG("expected either onto_name or *advance_name in this function");
    ++
    + 	if (onto_name) {
    + 		*onto = peel_committish(repo, onto_name, "--onto");
    + 		if (rinfo.positive_refexprs <
    +@@ builtin/replay.c: static struct commit *pick_regular_commit(struct repository *repo,
    + 	return create_commit(repo, result->tree, pickme, replayed_base);
      }
      
     +struct replay_revisions_options {
    @@ builtin/replay.c: static enum ref_action_mode get_ref_action_mode(struct reposit
     +	result->updates_nr++;
     +}
     +
    -+static int replay_revisions(struct repository *repo, struct rev_info *revs,
    ++static int replay_revisions(struct rev_info *revs,
     +			    struct replay_revisions_options *opts,
     +			    struct replay_result *out)
     +{
    @@ builtin/replay.c: static enum ref_action_mode get_ref_action_mode(struct reposit
     +	int ret;
     +
     +	advance = xstrdup_or_null(opts->advance);
    -+	set_up_replay_mode(repo, &revs->cmdline, opts->onto, &advance,
    ++	set_up_replay_mode(revs->repo, &revs->cmdline, opts->onto, &advance,
     +			   &onto, &update_refs);
     +
     +	/* FIXME: Should allow replaying commits with the first as a root commit */
    @@ builtin/replay.c: static enum ref_action_mode get_ref_action_mode(struct reposit
     +		goto out;
     +	}
     +
    -+	init_basic_merge_options(&merge_opt, repo);
    ++	init_basic_merge_options(&merge_opt, revs->repo);
     +	memset(&result, 0, sizeof(result));
     +	merge_opt.show_rename_progress = 0;
     +	last_commit = onto;
    @@ builtin/replay.c: static enum ref_action_mode get_ref_action_mode(struct reposit
     +		if (commit->parents->next)
     +			die(_("replaying merge commits is not supported yet!"));
     +
    -+		last_commit = pick_regular_commit(repo, commit, replayed_commits,
    ++		last_commit = pick_regular_commit(revs->repo, commit, replayed_commits,
     +						  onto, &merge_opt, &result);
     +		if (!last_commit)
     +			break;
    @@ builtin/replay.c: static enum ref_action_mode get_ref_action_mode(struct reposit
     +	return ret;
     +}
     +
    - static int handle_ref_update(enum ref_action_mode mode,
    - 			     struct ref_transaction *transaction,
    - 			     const char *refname,
    + static enum ref_action_mode parse_ref_action_mode(const char *ref_action, const char *source)
    + {
    + 	if (!ref_action || !strcmp(ref_action, "update"))
     @@ builtin/replay.c: int cmd_replay(int argc,
      	       const char *prefix,
      	       struct repository *repo)
    @@ builtin/replay.c: int cmd_replay(int argc,
     -				  contained, "--contained");
     +	die_for_incompatible_opt2(!!opts.advance, "--advance",
     +				  opts.contained, "--contained");
    ++	die_for_incompatible_opt2(!!opts.advance, "--advance",
    ++				  !!opts.onto, "--onto");
      
      	/* Parse ref action mode from command line or config */
      	ref_mode = get_ref_action_mode(repo, ref_action);
    @@ builtin/replay.c: int cmd_replay(int argc,
     -			   &onto, &update_refs);
     -
     -	/* FIXME: Should allow replaying commits with the first as a root commit */
    -+	ret = replay_revisions(repo, &revs, &opts, &result);
    ++	ret = replay_revisions(&revs, &opts, &result);
     +	if (ret)
     +		goto cleanup;

2: c5fca546e5 ! 2: 0945b53ecb builtin/replay: move core logic into "libgit.a"

    @@ builtin/replay.c
     -	if (!rinfo.positive_refexprs)
     -		die(_("need some commits to replay"));
     -
    --	die_for_incompatible_opt2(!!onto_name, "--onto",
    --				  !!*advance_name, "--advance");
    +-	if (!(!!onto_name ^ !!*advance_name))
    +-		BUG("expected either onto_name or *advance_name in this function");
    +-
     -	if (onto_name) {
     -		*onto = peel_committish(repo, onto_name, "--onto");
     -		if (rinfo.positive_refexprs <
    @@ builtin/replay.c
     -	return create_commit(repo, result->tree, pickme, replayed_base);
     -}
     -
    - static enum ref_action_mode parse_ref_action_mode(const char *ref_action, const char *source)
    - {
    - 	if (!ref_action || !strcmp(ref_action, "update"))
    -@@ builtin/replay.c: static enum ref_action_mode get_ref_action_mode(struct repository *repo, const c
    - 	return REF_ACTION_UPDATE;
    - }
    - 
     -struct replay_revisions_options {
     -	const char *advance;
     -	const char *onto;
    @@ builtin/replay.c: static enum ref_action_mode get_ref_action_mode(struct reposit
     -	result->updates_nr++;
     -}
     -
    --static int replay_revisions(struct repository *repo, struct rev_info *revs,
    +-static int replay_revisions(struct rev_info *revs,
     -			    struct replay_revisions_options *opts,
     -			    struct replay_result *out)
     -{
    @@ builtin/replay.c: static enum ref_action_mode get_ref_action_mode(struct reposit
     -	int ret;
     -
     -	advance = xstrdup_or_null(opts->advance);
    --	set_up_replay_mode(repo, &revs->cmdline, opts->onto, &advance,
    +-	set_up_replay_mode(revs->repo, &revs->cmdline, opts->onto, &advance,
     -			   &onto, &update_refs);
     -
     -	/* FIXME: Should allow replaying commits with the first as a root commit */
    @@ builtin/replay.c: static enum ref_action_mode get_ref_action_mode(struct reposit
     -		goto out;
     -	}
     -
    --	init_basic_merge_options(&merge_opt, repo);
    +-	init_basic_merge_options(&merge_opt, revs->repo);
     -	memset(&result, 0, sizeof(result));
     -	merge_opt.show_rename_progress = 0;
     -	last_commit = onto;
    @@ builtin/replay.c: static enum ref_action_mode get_ref_action_mode(struct reposit
     -		if (commit->parents->next)
     -			die(_("replaying merge commits is not supported yet!"));
     -
    --		last_commit = pick_regular_commit(repo, commit, replayed_commits,
    +-		last_commit = pick_regular_commit(revs->repo, commit, replayed_commits,
     -						  onto, &merge_opt, &result);
     -		if (!last_commit)
     -			break;
    @@ builtin/replay.c: static enum ref_action_mode get_ref_action_mode(struct reposit
     -	return ret;
     -}
     -
    - static int handle_ref_update(enum ref_action_mode mode,
    - 			     struct ref_transaction *transaction,
    - 			     const char *refname,
    + static enum ref_action_mode parse_ref_action_mode(const char *ref_action, const char *source)
    + {
    + 	if (!ref_action || !strcmp(ref_action, "update"))
     
      ## meson.build ##
     @@ meson.build: libgit_sources = [
    @@ replay.c (new)
     +#include "hex.h"
     +#include "merge-ort.h"
     +#include "object-name.h"
    -+#include "oidset.h"
    -+#include "parse-options.h"
     +#include "refs.h"
     +#include "replay.h"
     +#include "revision.h"
    ++#include "strmap.h"
     +#include "tree.h"
     +
     +static const char *short_commit_name(struct repository *repo,
    @@ replay.c (new)
     +	if (!rinfo.positive_refexprs)
     +		die(_("need some commits to replay"));
     +
    -+	die_for_incompatible_opt2(!!onto_name, "--onto",
    -+				  !!*advance_name, "--advance");
    ++	if (!(!!onto_name ^ !!*advance_name))
    ++		BUG("expected either onto_name or *advance_name in this function");
    ++
     +	if (onto_name) {
     +		*onto = peel_committish(repo, onto_name, "--onto");
     +		if (rinfo.positive_refexprs <
    @@ replay.c (new)
     +	result->updates_nr++;
     +}
     +
    -+int replay_revisions(struct repository *repo, struct rev_info *revs,
    ++int replay_revisions(struct rev_info *revs,
     +		     struct replay_revisions_options *opts,
     +		     struct replay_result *out)
     +{
    @@ replay.c (new)
     +	int ret;
     +
     +	advance = xstrdup_or_null(opts->advance);
    -+	set_up_replay_mode(repo, &revs->cmdline, opts->onto, &advance,
    ++	set_up_replay_mode(revs->repo, &revs->cmdline, opts->onto, &advance,
     +			   &onto, &update_refs);
     +
     +	/* FIXME: Should allow replaying commits with the first as a root commit */
    @@ replay.c (new)
     +		goto out;
     +	}
     +
    -+	init_basic_merge_options(&merge_opt, repo);
    ++	init_basic_merge_options(&merge_opt, revs->repo);
     +	memset(&result, 0, sizeof(result));
     +	merge_opt.show_rename_progress = 0;
     +	last_commit = onto;
    @@ replay.c (new)
     +		if (commit->parents->next)
     +			die(_("replaying merge commits is not supported yet!"));
     +
    -+		last_commit = pick_regular_commit(repo, commit, replayed_commits,
    ++		last_commit = pick_regular_commit(revs->repo, commit, replayed_commits,
     +						  onto, &merge_opt, &result);
     +		if (!last_commit)
     +			break;
    @@ replay.h (new)
     + *
     + * Returns 0 on success, a negative error code otherwise.
     + */
    -+int replay_revisions(struct repository *repo, struct rev_info *revs,
    ++int replay_revisions(struct rev_info *revs,
     +		     struct replay_revisions_options *opts,
     +		     struct replay_result *out);
     +
3:  1d55aab054 = 3:  85ebe5853f replay: small set of cleanups
4:  451717f951 < -:  ---------- replay: yield the object ID of the final rewritten commit
-:  ---------- > 4:  a24641dbfb replay: support empty commit ranges
-:  ---------- > 5:  e0ab803a46 replay: support updating detached HEAD
5:  7cde288c8d = 6:  abc33b25ca wt-status: provide function to expose status for trees
6:  b315c04169 ! 7:  387d1ded10 builtin: add new "history" command

@@ Documentation/git-history.adoc (new)
+your commit history that is simpler to use compared to linkgit:git-rebase[1] in +general.
+
-+If you want to reapply a range of commits onto a different base, or interactive -+rebases if you want to edit a range of commits.
++Use linkgit:git-rebase[1] if you want to reapply a range of commits onto a ++different base, or interactive rebases if you want to edit a range of commits ++at once.
+
+LIMITATIONS
+-----------
@@ Documentation/git-history.adoc (new)
+COMMANDS
+--------
+
-+Several commands are available to rewrite history in different ways:
++No commands are supported yet.
+
+GIT
+---
7: f71911586d ! 8: aeb895475b builtin/history: implement "reword" subcommand

    @@ Commit message
             rewritten. This especially helps with workflows that use stacked
             branches.
     
    +    Helped-by: Elijah Newren <[email protected]>
         Signed-off-by: Patrick Steinhardt <[email protected]>
     
      ## Documentation/git-history.adoc ##
    @@ Documentation/git-history.adoc: git-history - EXPERIMENTAL: Rewrite history
      
      DESCRIPTION
      -----------
    -@@ Documentation/git-history.adoc: Overall, linkgit:git-history[1] aims to provide a more opinionated way to modify
    - your commit history that is simpler to use compared to linkgit:git-rebase[1] in
    - general.
    - 
    --If you want to reapply a range of commits onto a different base, or interactive
    --rebases if you want to edit a range of commits.
    -+Use linkgit:git-rebase[1] if you want to reapply a range of commits onto a
    -+different base, or interactive rebases if you want to edit a range of commits
    -+at once.
    - 
    - LIMITATIONS
    - -----------
    -@@ Documentation/git-history.adoc: COMMANDS
    - 
    - Several commands are available to rewrite history in different ways:
    +@@ Documentation/git-history.adoc: first-class conflicts.
    + COMMANDS
    + --------
      
    +-No commands are supported yet.
    ++The following commands are available to rewrite history in different ways:
    ++
     +`reword <commit>`::
     +	Rewrite the commit message of the specified commit. All the other
     +	details of this commit remain unchanged. This command will spawn an
    @@ Documentation/git-history.adoc: COMMANDS
     +`--ref-action=(branches|head|print)`::
     +	Control which references will be updated by the command, if any. With
     +	`branches`, all local branches that point to commits which are
    -+	decendants of the original commit will be rewritten. With `head`, only
    ++	descendants of the original commit will be rewritten. With `head`, only
     +	the current `HEAD` reference will be rewritten. With `print`, all
     +	updates as they would be performed with `branches` are printed in a
     +	format that can be consumed by linkgit:git-update-ref[1].
    -+
    + 
      GIT
      ---
    - Part of the linkgit:git[1] suite
     
      ## builtin/history.c ##
     @@
    @@ builtin/history.c
     +					   struct commit *original,
     +					   struct commit **out)
     +{
    -+	const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
    ++	const char *exclude_gpgsig[] = {
    ++		/* We reencode the message, so the encoding needs to be stripped. */
    ++		"encoding",
    ++		/* We need to strip signatures as those will become invalid. */
    ++		"gpgsig",
    ++		"gpgsig-sha256",
    ++		NULL,
    ++	};
     +	const char *original_message, *original_body, *ptr;
     +	struct commit_extra_header *original_extra_headers = NULL;
     +	struct strbuf commit_message = STRBUF_INIT;
    @@ builtin/history.c
     +{
     +	const struct name_decoration *decoration;
     +	struct replay_revisions_options opts = { 0 };
    -+	struct replay_result result = {
    -+		.final_oid = rewritten->object.oid,
    -+	};
    ++	struct replay_result result = { 0 };
     +	struct ref_transaction *transaction = NULL;
     +	struct strvec args = STRVEC_INIT;
     +	struct strbuf err = STRBUF_INIT;
     +	struct commit *head = NULL;
     +	struct rev_info revs;
     +	char hex[GIT_MAX_HEXSZ + 1];
    ++	bool detached_head;
    ++	int head_flags = 0;
     +	int ret;
     +
    ++	refs_read_ref_full(get_main_ref_store(repo), "HEAD",
    ++			   RESOLVE_REF_NO_RECURSE, NULL, &head_flags);
    ++	detached_head = !(head_flags & REF_ISSYMREF);
    ++
     +	repo_init_revisions(repo, &revs, NULL);
     +	strvec_push(&args, "ignored");
     +	strvec_push(&args, "--reverse");
    @@ builtin/history.c
     +			goto out;
     +		}
     +
    -+		strvec_push(&args, oid_to_hex(&head->object.oid));
    ++		strvec_push(&args, "HEAD");
     +	} else {
     +		strvec_push(&args, "--branches");
    ++		strvec_push(&args, "HEAD");
     +	}
     +
     +	setup_revisions_from_strvec(&args, &revs, NULL);
    @@ builtin/history.c
     +
     +	opts.onto = oid_to_hex_r(hex, &rewritten->object.oid);
     +
    -+	ret = replay_revisions(repo, &revs, &opts, &result);
    ++	ret = replay_revisions(&revs, &opts, &result);
     +	if (ret)
     +		goto out;
     +
     +	switch (action) {
    -+	case REF_ACTION_DEFAULT:
     +	case REF_ACTION_BRANCHES:
    ++	case REF_ACTION_HEAD:
     +		transaction = ref_store_transaction_begin(get_main_ref_store(repo), 0, &err);
     +		if (!transaction) {
     +			ret = error(_("failed to begin ref transaction: %s"), err.buf);
    @@ builtin/history.c
     +		     decoration;
     +		     decoration = decoration->next)
     +		{
    -+			if (decoration->type != DECORATION_REF_LOCAL)
    ++			if (decoration->type != DECORATION_REF_LOCAL &&
    ++			    decoration->type != DECORATION_REF_HEAD)
    ++				continue;
    ++
    ++			if (action == REF_ACTION_HEAD &&
    ++			    decoration->type != DECORATION_REF_HEAD)
    ++				continue;
    ++
    ++			/*
    ++			 * We only need to update HEAD separately in case it's
    ++			 * detached. If it's not we'd already update the branch
    ++			 * it is pointing to.
    ++			 */
    ++			if (action == REF_ACTION_BRANCHES &&
    ++			    decoration->type == DECORATION_REF_HEAD &&
    ++			    !detached_head)
     +				continue;
     +
     +			ret = ref_transaction_update(transaction,
    @@ builtin/history.c
     +		}
     +
     +		break;
    -+	case REF_ACTION_HEAD:
    -+		ret = refs_update_ref(get_main_ref_store(repo), reflog_msg, "HEAD",
    -+				      &result.final_oid, &head->object.oid, 0,
    -+				      UPDATE_REFS_MSG_ON_ERR);
    -+		if (ret)
    -+			goto out;
    -+		break;
     +	case REF_ACTION_PRINT:
     +		for (size_t i = 0; i < result.updates_nr; i++)
     +			printf("update %s %s %s\n",
    @@ builtin/history.c
     +	}
     +	repo_config(repo, git_default_config, NULL);
     +
    ++	if (action == REF_ACTION_DEFAULT)
    ++		action = REF_ACTION_BRANCHES;
    ++
     +	original = lookup_commit_reference_by_name(argv[0]);
     +	if (!original) {
     +		ret = error(_("commit cannot be found: %s"), argv[0]);
    @@ builtin/history.c
     +	return fn(argc, argv, prefix, repo);
      }
     
    - ## replay.c ##
    -@@ replay.c: int replay_revisions(struct repository *repo, struct rev_info *revs,
    - 	struct commit *commit;
    - 	struct commit *onto = NULL;
    - 	struct merge_options merge_opt;
    --	struct merge_result result;
    -+	struct merge_result result = {
    -+		.clean = 1,
    -+	};
    - 	char *advance;
    - 	int ret;
    - 
    -@@ replay.c: int replay_revisions(struct repository *repo, struct rev_info *revs,
    - 	}
    - 
    - 	init_basic_merge_options(&merge_opt, repo);
    --	memset(&result, 0, sizeof(result));
    - 	merge_opt.show_rename_progress = 0;
    - 	last_commit = onto;
    - 	replayed_commits = kh_init_oid_map();
    -
      ## t/meson.build ##
     @@ t/meson.build: integration_tests = [
        't3437-rebase-fixup-options.sh',
    @@ t/t3451-history-reword.sh (new)
     +	)
     +'
     +
    ++test_expect_success 'can reword commit in the middle even on detached head' '
    ++	test_when_finished "rm -rf repo" &&
    ++	git init repo &&
    ++	(
    ++		cd repo &&
    ++		test_commit first &&
    ++		test_commit second &&
    ++		test_commit third_on_main &&
    ++		git checkout --detach HEAD^ &&
    ++		test_commit third_on_head &&
    ++
    ++		reword_with_message HEAD~ <<-EOF &&
    ++		second reworded
    ++		EOF
    ++
    ++		expect_graph HEAD --branches <<-\EOF
    ++		* third_on_head
    ++		| * third_on_main
    ++		|/
    ++		* second reworded
    ++		* first
    ++		EOF
    ++       )
    ++'
    ++
    ++test_expect_success 'can reword the detached head' '
    ++	test_when_finished "rm -rf repo" &&
    ++	git init repo &&
    ++	(
    ++		cd repo &&
    ++		test_commit first &&
    ++		test_commit second &&
    ++		git checkout --detach HEAD &&
    ++		test_commit third &&
    ++
    ++		reword_with_message HEAD <<-EOF &&
    ++		third reworded
    ++		EOF
    ++
    ++		expect_log <<-\EOF
    ++		third reworded
    ++		second
    ++		first
    ++		EOF
    ++	)
    ++'
    ++
     +test_expect_success 'can reword root commit' '
     +	test_when_finished "rm -rf repo" &&
     +	git init repo &&

---
base-commit: 02bdc12118c43e0a65258eb742492965859bffb6
change-id: 20250819-b4-pks-history-builtin-83398f9a05f0

#326 lore raw

PATCH v10 1/8 builtin/replay: extract core logic to replay revisions

We're about to move the core logic used to replay revisions onto a new base into the "libgit.a" library. Prepare for this by pulling out the logic into a new function replay_revisions() that:

1. Takes a set of revisions to replay and some options that tell it how it ought to replay the revisions.

2. Replays the commits.

3. Records any reference updates that would be caused by replaying the commits in a structure that is owned by the caller.

The logic itself will be moved into a separate file in the next commit. This change is not expected to cause user-visible change in behaviour.

---
 builtin/replay.c | 281 +++++++++++++++++++++++++++++++++----------------------
 1 file changed, 170 insertions(+), 111 deletions(-)
builtin/replay.c +170 -111
index 1960bbbee8..df0dc04d02 100644
@@ -177,8 +177,9 @@ static void set_up_replay_mode(struct repository *repo,
 	if (!rinfo.positive_refexprs)
 		die(_("need some commits to replay"));
 
-	die_for_incompatible_opt2(!!onto_name, "--onto",
-				  !!*advance_name, "--advance");
+	if (!(!!onto_name ^ !!*advance_name))
+		BUG("expected either onto_name or *advance_name in this function");
+
 	if (onto_name) {
 		*onto = peel_committish(repo, onto_name, "--onto");
 		if (rinfo.positive_refexprs <
@@ -253,6 +254,137 @@ static struct commit *pick_regular_commit(struct repository *repo,
 	return create_commit(repo, result->tree, pickme, replayed_base);
 }
 
+struct replay_revisions_options {
+	const char *advance;
+	const char *onto;
+	int contained;
+};
+
+struct replay_result {
+	struct replay_ref_update {
+		char *refname;
+		struct object_id old_oid;
+		struct object_id new_oid;
+	} *updates;
+	size_t updates_nr, updates_alloc;
+
+	bool merge_conflict;
+};
+
+static void replay_result_release(struct replay_result *result)
+{
+	for (size_t i = 0; i < result->updates_nr; i++)
+		free(result->updates[i].refname);
+	free(result->updates);
+}
+
+static void replay_result_queue_update(struct replay_result *result,
+				       const char *refname,
+				       const struct object_id *old_oid,
+				       const struct object_id *new_oid)
+{
+	ALLOC_GROW(result->updates, result->updates_nr + 1, result->updates_alloc);
+	result->updates[result->updates_nr].refname = xstrdup(refname);
+	result->updates[result->updates_nr].old_oid = *old_oid;
+	result->updates[result->updates_nr].new_oid = *new_oid;
+	result->updates_nr++;
+}
+
+static int replay_revisions(struct rev_info *revs,
+			    struct replay_revisions_options *opts,
+			    struct replay_result *out)
+{
+	kh_oid_map_t *replayed_commits = NULL;
+	struct strset *update_refs = NULL;
+	struct commit *last_commit = NULL;
+	struct commit *commit;
+	struct commit *onto = NULL;
+	struct merge_options merge_opt;
+	struct merge_result result;
+	char *advance;
+	int ret;
+
+	advance = xstrdup_or_null(opts->advance);
+	set_up_replay_mode(revs->repo, &revs->cmdline, opts->onto, &advance,
+			   &onto, &update_refs);
+
+	/* FIXME: Should allow replaying commits with the first as a root commit */
+
+	if (prepare_revision_walk(revs) < 0) {
+		ret = error(_("error preparing revisions"));
+		goto out;
+	}
+
+	init_basic_merge_options(&merge_opt, revs->repo);
+	memset(&result, 0, sizeof(result));
+	merge_opt.show_rename_progress = 0;
+	last_commit = onto;
+	replayed_commits = kh_init_oid_map();
+	while ((commit = get_revision(revs))) {
+		const struct name_decoration *decoration;
+		khint_t pos;
+		int hr;
+
+		if (!commit->parents)
+			die(_("replaying down from root commit is not supported yet!"));
+		if (commit->parents->next)
+			die(_("replaying merge commits is not supported yet!"));
+
+		last_commit = pick_regular_commit(revs->repo, commit, replayed_commits,
+						  onto, &merge_opt, &result);
+		if (!last_commit)
+			break;
+
+		/* Record commit -> last_commit mapping */
+		pos = kh_put_oid_map(replayed_commits, commit->object.oid, &hr);
+		if (hr == 0)
+			BUG("Duplicate rewritten commit: %s\n",
+			    oid_to_hex(&commit->object.oid));
+		kh_value(replayed_commits, pos) = last_commit;
+
+		/* Update any necessary branches */
+		if (advance)
+			continue;
+		decoration = get_name_decoration(&commit->object);
+		if (!decoration)
+			continue;
+		while (decoration) {
+			if (decoration->type == DECORATION_REF_LOCAL &&
+			    (opts->contained || strset_contains(update_refs,
+								decoration->name))) {
+				replay_result_queue_update(out, decoration->name,
+							   &commit->object.oid,
+							   &last_commit->object.oid);
+			}
+			decoration = decoration->next;
+		}
+	}
+
+	if (!result.clean) {
+		out->merge_conflict = true;
+		ret = -1;
+		goto out;
+	}
+
+	/* In --advance mode, advance the target ref */
+	if (advance)
+		replay_result_queue_update(out, advance,
+					   &onto->object.oid,
+					   &last_commit->object.oid);
+
+	ret = 0;
+
+out:
+	if (update_refs) {
+		strset_clear(update_refs);
+		free(update_refs);
+	}
+	kh_destroy_oid_map(replayed_commits);
+	merge_finalize(&merge_opt, &result);
+	free(advance);
+	return ret;
+}
+
 static enum ref_action_mode parse_ref_action_mode(const char *ref_action, const char *source)
 {
 	if (!ref_action || !strcmp(ref_action, "update"))
@@ -306,21 +438,11 @@ int cmd_replay(int argc,
 	       const char *prefix,
 	       struct repository *repo)
 {
-	const char *advance_name_opt = NULL;
-	char *advance_name = NULL;
-	struct commit *onto = NULL;
-	const char *onto_name = NULL;
-	int contained = 0;
+	struct replay_revisions_options opts = { 0 };
+	struct replay_result result = { 0 };
 	const char *ref_action = NULL;
 	enum ref_action_mode ref_mode;
-
 	struct rev_info revs;
-	struct commit *last_commit = NULL;
-	struct commit *commit;
-	struct merge_options merge_opt;
-	struct merge_result result;
-	struct strset *update_refs = NULL;
-	kh_oid_map_t *replayed_commits;
 	struct ref_transaction *transaction = NULL;
 	struct strbuf transaction_err = STRBUF_INIT;
 	struct strbuf reflog_msg = STRBUF_INIT;
@@ -333,13 +455,13 @@ int cmd_replay(int argc,
 		NULL
 	};
 	struct option replay_options[] = {
-		OPT_STRING(0, "advance", &advance_name_opt,
+		OPT_STRING(0, "advance", &opts.advance,
 			   N_("branch"),
 			   N_("make replay advance given branch")),
-		OPT_STRING(0, "onto", &onto_name,
+		OPT_STRING(0, "onto", &opts.onto,
 			   N_("revision"),
 			   N_("replay onto given commit")),
-		OPT_BOOL(0, "contained", &contained,
+		OPT_BOOL(0, "contained", &opts.contained,
 			 N_("update all branches that point at commits in <revision-range>")),
 		OPT_STRING(0, "ref-action", &ref_action,
 			   N_("mode"),
@@ -350,19 +472,19 @@ int cmd_replay(int argc,
 	argc = parse_options(argc, argv, prefix, replay_options, replay_usage,
 			     PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN_OPT);
 
-	if (!onto_name && !advance_name_opt) {
+	if (!opts.onto && !opts.advance) {
 		error(_("option --onto or --advance is mandatory"));
 		usage_with_options(replay_usage, replay_options);
 	}
 
-	die_for_incompatible_opt2(!!advance_name_opt, "--advance",
-				  contained, "--contained");
+	die_for_incompatible_opt2(!!opts.advance, "--advance",
+				  opts.contained, "--contained");
+	die_for_incompatible_opt2(!!opts.advance, "--advance",
+				  !!opts.onto, "--onto");
 
 	/* Parse ref action mode from command line or config */
 	ref_mode = get_ref_action_mode(repo, ref_action);
 
-	advance_name = xstrdup_or_null(advance_name_opt);
-
 	repo_init_revisions(repo, &revs, prefix);
 
 	/*
@@ -414,18 +536,19 @@ int cmd_replay(int argc,
 		revs.simplify_history = 0;
 	}
 
-	set_up_replay_mode(repo, &revs.cmdline,
-			   onto_name, &advance_name,
-			   &onto, &update_refs);
-
-	/* FIXME: Should allow replaying commits with the first as a root commit */
+	ret = replay_revisions(&revs, &opts, &result);
+	if (ret)
+		goto cleanup;
 
 	/* Build reflog message */
-	if (advance_name_opt)
-		strbuf_addf(&reflog_msg, "replay --advance %s", advance_name_opt);
-	else
-		strbuf_addf(&reflog_msg, "replay --onto %s",
-			    oid_to_hex(&onto->object.oid));
+	if (opts.advance) {
+		strbuf_addf(&reflog_msg, "replay --advance %s", opts.advance);
+	} else {
+		struct object_id oid;
+		if (repo_get_oid_committish(repo, opts.onto, &oid))
+			BUG("--onto commit should have been resolved beforehand already");
+		strbuf_addf(&reflog_msg, "replay --onto %s", oid_to_hex(&oid));
+	}
 
 	/* Initialize ref transaction if using update mode */
 	if (ref_mode == REF_ACTION_UPDATE) {
@@ -438,78 +561,19 @@ int cmd_replay(int argc,
 		}
 	}
 
-	if (prepare_revision_walk(&revs) < 0) {
-		ret = error(_("error preparing revisions"));
-		goto cleanup;
-	}
-
-	init_basic_merge_options(&merge_opt, repo);
-	memset(&result, 0, sizeof(result));
-	merge_opt.show_rename_progress = 0;
-	last_commit = onto;
-	replayed_commits = kh_init_oid_map();
-	while ((commit = get_revision(&revs))) {
-		const struct name_decoration *decoration;
-		khint_t pos;
-		int hr;
-
-		if (!commit->parents)
-			die(_("replaying down from root commit is not supported yet!"));
-		if (commit->parents->next)
-			die(_("replaying merge commits is not supported yet!"));
-
-		last_commit = pick_regular_commit(repo, commit, replayed_commits,
-						  onto, &merge_opt, &result);
-		if (!last_commit)
-			break;
-
-		/* Record commit -> last_commit mapping */
-		pos = kh_put_oid_map(replayed_commits, commit->object.oid, &hr);
-		if (hr == 0)
-			BUG("Duplicate rewritten commit: %s\n",
-			    oid_to_hex(&commit->object.oid));
-		kh_value(replayed_commits, pos) = last_commit;
-
-		/* Update any necessary branches */
-		if (advance_name)
-			continue;
-		decoration = get_name_decoration(&commit->object);
-		if (!decoration)
-			continue;
-		while (decoration) {
-			if (decoration->type == DECORATION_REF_LOCAL &&
-			    (contained || strset_contains(update_refs,
-							  decoration->name))) {
-				if (handle_ref_update(ref_mode, transaction,
-						      decoration->name,
-						      &last_commit->object.oid,
-						      &commit->object.oid,
-						      reflog_msg.buf,
-						      &transaction_err) < 0) {
-					ret = error(_("failed to update ref '%s': %s"),
-						    decoration->name, transaction_err.buf);
-					goto cleanup;
-				}
-			}
-			decoration = decoration->next;
-		}
-	}
-
-	/* In --advance mode, advance the target ref */
-	if (result.clean == 1 && advance_name) {
-		if (handle_ref_update(ref_mode, transaction, advance_name,
-				      &last_commit->object.oid,
-				      &onto->object.oid,
-				      reflog_msg.buf,
-				      &transaction_err) < 0) {
+	for (size_t i = 0; i < result.updates_nr; i++) {
+		ret = handle_ref_update(ref_mode, transaction, result.updates[i].refname,
+					&result.updates[i].new_oid, &result.updates[i].old_oid,
+					reflog_msg.buf, &transaction_err);
+		if (ret) {
 			ret = error(_("failed to update ref '%s': %s"),
-				    advance_name, transaction_err.buf);
+				    result.updates[i].refname, transaction_err.buf);
 			goto cleanup;
 		}
 	}
 
 	/* Commit the ref transaction if we have one */
-	if (transaction && result.clean == 1) {
+	if (transaction) {
 		if (ref_transaction_commit(transaction, &transaction_err)) {
 			ret = error(_("failed to commit ref transaction: %s"),
 				    transaction_err.buf);
@@ -517,24 +581,19 @@ int cmd_replay(int argc,
 		}
 	}
 
-	merge_finalize(&merge_opt, &result);
-	kh_destroy_oid_map(replayed_commits);
-	if (update_refs) {
-		strset_clear(update_refs);
-		free(update_refs);
-	}
-	ret = result.clean;
-
 cleanup:
 	if (transaction)
 		ref_transaction_free(transaction);
+	replay_result_release(&result);
 	strbuf_release(&transaction_err);
 	strbuf_release(&reflog_msg);
 	release_revisions(&revs);
-	free(advance_name);
 
-	/* Return */
-	if (ret < 0)
-		exit(128);
-	return ret ? 0 : 1;
+	if (ret) {
+		if (result.merge_conflict)
+			return 1;
+		return 128;
+	}
+
+	return 0;
 }
Signature · 1 line
2.52.0.590.g1f87b77810.dirty
#327 lore raw

Re: [PATCH v10 1/8] builtin/replay: extract core logic to replay revisions

builtin/replay.c static void set_up_replay_mode(struct repository *repo, · line 181

Quoted 4 lines · Patrick Steinhardt
builtin/replay.c +2 -2
-	die_for_incompatible_opt2(!!onto_name, "--onto",
-				  !!*advance_name, "--advance");
+	if (!(!!onto_name ^ !!*advance_name))
+		BUG("expected either onto_name or *advance_name in this function");

This brings our crypticness to a whole new level. onto_name not being NULL is a sign that "--onto" was given, while *advance_name pointer points at the string that "--advance" option has received. We are saying that only one of these two must be non-NULL, and the other must be NULL.

I know !!VAR is an idiom to turn any pointer into 0 (=NULL) or 1 (!=NULL), but isn't the latter (i.e., normalizing all non-NULL pointer to 1) a bit overkill, which becomes only necessary because the construction wants to use "^" as "sides of this operator are different Boolean values" operator. And then to add on top, the whole thing is !(negated). I wonder if

	if (!onto_name != !*advance_name)
		BUG("one and only one of --onto/--advance must be given");

is easier to follow without being overly cute?

Thanks.

#328 lore raw

Re: [PATCH v10 1/8] builtin/replay: extract core logic to replay revisions

Quoted 20 lines · Junio C Hamano

builtin/replay.c static void set_up_replay_mode(struct repository *repo, · line 181

Quoted 4 lines · Patrick Steinhardt
builtin/replay.c +2 -2
-	die_for_incompatible_opt2(!!onto_name, "--onto",
-				  !!*advance_name, "--advance");
+	if (!(!!onto_name ^ !!*advance_name))
+		BUG("expected either onto_name or *advance_name in this function");

This brings our crypticness to a whole new level. onto_name not being NULL is a sign that "--onto" was given, while *advance_name pointer points at the string that "--advance" option has received. We are saying that only one of these two must be non-NULL, and the other must be NULL.

I know !!VAR is an idiom to turn any pointer into 0 (=NULL) or 1 (!=NULL), but isn't the latter (i.e., normalizing all non-NULL pointer to 1) a bit overkill, which becomes only necessary because the construction wants to use "^" as "sides of this operator are different Boolean values" operator. And then to add on top, the whole thing is !(negated). I wonder if

Quoted 4 lines
	if (!onto_name != !*advance_name)
		BUG("one and only one of --onto/--advance must be given");

is easier to follow without being overly cute?

It should be:

    if (!onto_name == !*advance_name)
        BUG(...);

But other than that it reads way better indeed. Fixed up locally, thanks!

Patrick

#329 lore raw

Re: [PATCH v10 1/8] builtin/replay: extract core logic to replay revisions

In reply to Patrick Steinhardt

On Mon, Jan 12, 2026 at 6:17 AM Patrick Steinhardt <[email protected]> wrote:
[...]

builtin/replay.c static void set_up_replay_mode(struct repository *repo, · line 182

Quoted 5 lines
builtin/replay.c +3 -2
-       die_for_incompatible_opt2(!!onto_name, "--onto",
-                                 !!*advance_name, "--advance");
+       if (!(!!onto_name ^ !!*advance_name))
+               BUG("expected either onto_name or *advance_name in this function");
+

I liked Junio's comments on this section and your response.

Quoted 1 line
(quoted diff) +0 -0
@@ -253,6 +254,137 @@ static struct commit *pick_regular_commit(struct repository *repo,

[...]

builtin/replay.c static struct commit *pick_regular_commit(struct repository *repo, · line 365

Quoted 3 lines
builtin/replay.c +3 -0
+       if (!result.clean) {
+               out->merge_conflict = true;
+               ret = -1;

Even if you keep the special merge_conflict field for other purposes, setting ret to -1 here still feels very wrong. Negative return codes, and especially -1, is used throughout the merge machinery to signal unexpected errors like failure to read/write to disk. Further, it's inconsistent with how builtin/merge-tree.c works, where both in code and in documentation merge result code is 0 == clean, 1 == merge conflicts. I'm worried using -1 here could cause some nasty future maintenance headaches trying to understand the field if left this way, at least for me. As mentioned in the last round, the ret value here should be 1.

Quoted 1 line
(quoted diff) +0 -0
@@ -306,21 +438,11 @@ int cmd_replay(int argc,

[...]

builtin/replay.c int cmd_replay(int argc, · line 481

Quoted 4 lines
builtin/replay.c +2 -2
-       die_for_incompatible_opt2(!!advance_name_opt, "--advance",
-                                 contained, "--contained");
+       die_for_incompatible_opt2(!!opts.advance, "--advance",
+                                 opts.contained, "--contained");

This predates your patch, but I'm wondering if there's anything we should do to clarify and/or simplify the first check. The original form of the check
+ die_for_incompatible_opt2(!!opts.advance, "--advance",
+ opts.contained, "--contained");
was created because (a) I had code that allowed --onto to be implicit in some cases, and (b) I was thinking only of --onto and --advance modes.

However: (a) we got rid of the implicit mode selection from my private branch, and (b) Siddharth added patches which added a --revert mode. Those patches caused confusion around the interplay of --contained with the new mode
(https://lore.kernel.org/git/[email protected]/). I thought the synopsis:

           "([--contained] --onto <newbase> | --advance <branch>) "

implied clearly enough that --contained is a sub-mode of --onto, but apparently that wasn't the case. Perhaps we can strengthen that understanding if we change the check here to instead be something like
if (opts.contained && !opts.onto)
die("--onto must be specified if --contained is")

Definitely not critical; but might be a nice cleanup.

Review

Quoted 2 lines
(quoted diff) +2 -0
+       die_for_incompatible_opt2(!!opts.advance, "--advance",
+                                 !!opts.onto, "--onto");

Yeah, and Siddharth can convert this to a die_for_incompatible_opt3() call, adding "--revert" to it when he rerolls his series on top of yours.

builtin/replay.c int cmd_replay(int argc, · line 599

Quoted 12 lines
builtin/replay.c +7 -4
-       /* Return */
-       if (ret < 0)
-               exit(128);
-       return ret ? 0 : 1;
+       if (ret) {
+               if (result.merge_conflict)
+                       return 1;
+               return 128;
+       }
+
+       return 0;
 }

You mentioned that you wanted to keep the merge_conflict field due to some future patches beyond the currently submitted series. I wonder if it'd make more sense to introduce that field once you introduce the new patches, but i don't feel too strongly about that. I do feel strongly that the place where you set ret to -1 is problematic and should be changed to 1.

#330 lore raw

Re: [PATCH v10 1/8] builtin/replay: extract core logic to replay revisions

Quoted 7 lines · Elijah Newren
Quoted 1 line · Patrick Steinhardt
(quoted diff) +0 -0
@@ -253,6 +254,137 @@ static struct commit *pick_regular_commit(struct repository *repo,

[...]

builtin/replay.c static struct commit *pick_regular_commit(struct repository *repo, · line 365

Quoted 3 lines
builtin/replay.c +3 -0
+       if (!result.clean) {
+               out->merge_conflict = true;
+               ret = -1;
Quoted 10 lines

Even if you keep the special merge_conflict field for other purposes, setting ret to -1 here still feels very wrong. Negative return codes, and especially -1, is used throughout the merge machinery to signal unexpected errors like failure to read/write to disk. Further, it's inconsistent with how builtin/merge-tree.c works, where both in code and in documentation merge result code is 0 == clean, 1 == merge conflicts. I'm worried using -1 here could cause some nasty future maintenance headaches trying to understand the field if left this way, at least for me. As mentioned in the last round, the ret value here should be 1.

To expand a bit why I prefer my style: it's extremely easy to get the return code wrong. We have a bunch of callsites that set the return code directly, and in theory we now have to vet every single such call site to verify that it will never return an error code of 1. If any function does, then exiting with 1 now becomes ambiguous. This is an error waiting to happen.

With being explicit about the error code and the specific condition we care about we make that issue go away. Furthermore, it also helps to document intent in the code as it is very explicit now.

In any case, I don't want this disagreement to block the patch series, so I'll adapt to make it return a positive value on a conflict.

Quoted 29 lines
Quoted 1 line
(quoted diff) +0 -0
@@ -306,21 +438,11 @@ int cmd_replay(int argc,

[...]

builtin/replay.c int cmd_replay(int argc, · line 481

Quoted 4 lines
builtin/replay.c +2 -2
-       die_for_incompatible_opt2(!!advance_name_opt, "--advance",
-                                 contained, "--contained");
+       die_for_incompatible_opt2(!!opts.advance, "--advance",
+                                 opts.contained, "--contained");

This predates your patch, but I'm wondering if there's anything we should do to clarify and/or simplify the first check. The original form of the check
+ die_for_incompatible_opt2(!!opts.advance, "--advance",
+ opts.contained, "--contained");
was created because (a) I had code that allowed --onto to be implicit in some cases, and (b) I was thinking only of --onto and --advance modes.

However: (a) we got rid of the implicit mode selection from my private branch, and (b) Siddharth added patches which added a --revert mode. Those patches caused confusion around the interplay of --contained with the new mode
(https://lore.kernel.org/git/[email protected]/). I thought the synopsis:

           "([--contained] --onto <newbase> | --advance <branch>) "

implied clearly enough that --contained is a sub-mode of --onto, but apparently that wasn't the case. Perhaps we can strengthen that understanding if we change the check here to instead be something like
if (opts.contained && !opts.onto)
die("--onto must be specified if --contained is")

Quoted 8 lines

Definitely not critical; but might be a nice cleanup.

Review

Quoted 2 lines
(quoted diff) +2 -0
+       die_for_incompatible_opt2(!!opts.advance, "--advance",
+                                 !!opts.onto, "--onto");

Yeah, and Siddharth can convert this to a die_for_incompatible_opt3() call, adding "--revert" to it when he rerolls his series on top of yours.

Fair, but this feels somewhat unrelated to my changes. So I'll not touch this part and leave it for a future patch series to clean up, if that's alright with you.

Quoted 13 lines

builtin/replay.c int cmd_replay(int argc, · line 599

Quoted 12 lines
builtin/replay.c +7 -4
-       /* Return */
-       if (ret < 0)
-               exit(128);
-       return ret ? 0 : 1;
+       if (ret) {
+               if (result.merge_conflict)
+                       return 1;
+               return 128;
+       }
+
+       return 0;
 }
Quoted 6 lines

You mentioned that you wanted to keep the merge_conflict field due to some future patches beyond the currently submitted series. I wonder if it'd make more sense to introduce that field once you introduce the new patches, but i don't feel too strongly about that. I do feel strongly that the place where you set ret to -1 is problematic and should be changed to 1.

I'll drop the field for now.

Patrick

#331 lore raw

PATCH v10 2/8 builtin/replay: move core logic into "libgit.a"

In reply to Patrick Steinhardt

Move the core logic used to replay commits into "libgit.a" so that it can be easily reused by other commands. It will be used in a subsequent commit where we're about to introduce a new git-history(1) command.

Note that with this change we have no sign-comparison warnings anymore, and neither do we depend on the_repository.

---
 Makefile         |   1 +
 builtin/replay.c | 369 +------------------------------------------------------
 meson.build      |   1 +
 replay.c         | 355 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 replay.h         |  64 ++++++++++
 5 files changed, 422 insertions(+), 368 deletions(-)
Makefile +1 -0
index b7eba509c6..1c64a5d2ae 100644
@@ -1285,6 +1285,7 @@ LIB_OBJS += repack-geometry.o
 LIB_OBJS += repack-midx.o
 LIB_OBJS += repack-promisor.o
 LIB_OBJS += replace-object.o
+LIB_OBJS += replay.o
 LIB_OBJS += repo-settings.o
 LIB_OBJS += repository.o
 LIB_OBJS += rerere.o
builtin/replay.c +1 -368

390 lines not on this page · raw message

meson.build +1 -0
index dd52efd1c8..a5a4e99b25 100644
@@ -471,6 +471,7 @@ libgit_sources = [
   'repack-midx.c',
   'repack-promisor.c',
   'replace-object.c',
+  'replay.c',
   'repo-settings.c',
   'repository.c',
   'rerere.c',
replay.c new file +355 -0

355 lines not on this page · raw message

replay.h new file +64 -0

64 lines not on this page · raw message

Signature · 1 line
2.52.0.590.g1f87b77810.dirty
#332 lore raw

PATCH v10 3/8 replay: small set of cleanups

In reply to Patrick Steinhardt

Perform a small set of cleanups so that the "replay" logic compiles with "-Wsign-compare" and doesn't use the_repository anymore. Note that there are still some implicit dependencies on the_repository, e.g. because we use get_commit_output_encoding().

---
 replay.c | 11 ++++-------
 1 file changed, 4 insertions(+), 7 deletions(-)
replay.c +4 -7
index f7c61dd83f..1e660171d2 100644
@@ -1,5 +1,4 @@
 #define USE_THE_REPOSITORY_VARIABLE
-#define DISABLE_SIGN_COMPARE_WARNINGS
 
 #include "git-compat-util.h"
 #include "environment.h"
@@ -78,7 +77,7 @@ static struct commit *create_commit(struct repository *repo,
 	obj = parse_object(repo, &ret);
 
 out:
-	repo_unuse_commit_buffer(the_repository, based_on, message);
+	repo_unuse_commit_buffer(repo, based_on, message);
 	free_commit_extra_headers(extra);
 	free_commit_list(parents);
 	strbuf_release(&msg);
@@ -90,16 +89,14 @@ struct ref_info {
 	struct commit *onto;
 	struct strset positive_refs;
 	struct strset negative_refs;
-	int positive_refexprs;
-	int negative_refexprs;
+	size_t positive_refexprs;
+	size_t negative_refexprs;
 };
 
 static void get_ref_information(struct repository *repo,
 				struct rev_cmdline_info *cmd_info,
 				struct ref_info *ref_info)
 {
-	int i;
-
 	ref_info->onto = NULL;
 	strset_init(&ref_info->positive_refs);
 	strset_init(&ref_info->negative_refs);
@@ -121,7 +118,7 @@ static void get_ref_information(struct repository *repo,
 	 * the second because they'd likely just be replaying commits on top
 	 * of the same commit and not making any difference.
 	 */
-	for (i = 0; i < cmd_info->nr; i++) {
+	for (size_t i = 0; i < cmd_info->nr; i++) {
 		struct rev_cmdline_entry *e = cmd_info->rev + i;
 		struct object_id oid;
 		const char *refexpr = e->name;
Signature · 1 line
2.52.0.590.g1f87b77810.dirty
#333 lore raw

PATCH v10 4/8 replay: support empty commit ranges

In reply to Patrick Steinhardt

In a subsequent commit we're about to introduce a new user of the replay subsystem. With that new user, the range of commits that we'll want to replay will be identified implicitly via "HEAD". With such implicit ranges it becomes likely that the range of revisions that we're asked to replay becomes empty. This case does not make sense with git-replay(1), but with the new command it will.

This case is not currently supported by replay_revisions() though because we zero-initialize struct merge_result. This includes its .clean member, which indicates whether the merge ran into a conflict or not. But given that we don't have any revision to replay, we won't ever perform any merge at all, and consequently that member will never be set to 1. We thus later think that there's been a merge conflict and return an error from replay_commits().

Address this issue by initializing the .clean member to 1.

---
 replay.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
replay.c +3 -2
index 1e660171d2..a8e6d5b30b 100644
@@ -266,7 +266,9 @@ int replay_revisions(struct rev_info *revs,
 	struct commit *commit;
 	struct commit *onto = NULL;
 	struct merge_options merge_opt;
-	struct merge_result result;
+	struct merge_result result = {
+		.clean = 1,
+	};
 	char *advance;
 	int ret;
 
@@ -282,7 +284,6 @@ int replay_revisions(struct rev_info *revs,
 	}
 
 	init_basic_merge_options(&merge_opt, revs->repo);
-	memset(&result, 0, sizeof(result));
 	merge_opt.show_rename_progress = 0;
 	last_commit = onto;
 	replayed_commits = kh_init_oid_map();
Signature · 1 line
2.52.0.590.g1f87b77810.dirty
#334 lore raw

Re: [PATCH v10 4/8] replay: support empty commit ranges

Quoted 7 lines · Patrick Steinhardt

In a subsequent commit we're about to introduce a new user of the replay subsystem. With that new user, the range of commits that we'll want to replay will be identified implicitly via "HEAD". With such implicit ranges it becomes likely that the range of revisions that we're asked to replay becomes empty. This case does not make sense with git-replay(1), but with the new command it will.

I think I know what you were trying to say, but this feels misleading; it could be the commit at the tip of any branch, not just HEAD. Perhaps:

In a subsequent commit we're about to introduce a new user of the replay subsystem. With that new user, the range of commits that we'll want to replay will be identified implicitly via a single commit, and will include all descendants of that commit to any branch. If that commit has no descendants (because it's the tip of some branch), then the range of revisions that we're asked to replay becomes empty. This case does not make sense with git-replay(1), but with the new command it will.

Quoted 40 lines

This case is not currently supported by replay_revisions() though because we zero-initialize struct merge_result. This includes its .clean member, which indicates whether the merge ran into a conflict or not. But given that we don't have any revision to replay, we won't ever perform any merge at all, and consequently that member will never be set to 1. We thus later think that there's been a merge conflict and return an error from replay_commits().

Address this issue by initializing the .clean member to 1.

---
 replay.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
replay.c +3 -3
index 1e660171d2..a8e6d5b30b 100644
@@ -266,7 +266,9 @@ int replay_revisions(struct rev_info *revs,
        struct commit *commit;
        struct commit *onto = NULL;
        struct merge_options merge_opt;
-       struct merge_result result;
+       struct merge_result result = {
+               .clean = 1,
+       };
        char *advance;
        int ret;
 
@@ -282,7 +284,6 @@ int replay_revisions(struct rev_info *revs,
        }
 
        init_basic_merge_options(&merge_opt, revs->repo);
-       memset(&result, 0, sizeof(result));
        merge_opt.show_rename_progress = 0;
        last_commit = onto;
        replayed_commits = kh_init_oid_map();
 
--
Quoted 1 line

2.52.0.590.g1f87b77810.dirty

Looks good otherwise; thanks for splitting this out.

#335 lore raw

Re: [PATCH v10 4/8] replay: support empty commit ranges

Quoted 13 lines · Elijah Newren
Quoted 7 lines · Patrick Steinhardt

In a subsequent commit we're about to introduce a new user of the replay subsystem. With that new user, the range of commits that we'll want to replay will be identified implicitly via "HEAD". With such implicit ranges it becomes likely that the range of revisions that we're asked to replay becomes empty. This case does not make sense with git-replay(1), but with the new command it will.

I think I know what you were trying to say, but this feels misleading; it could be the commit at the tip of any branch, not just HEAD. Perhaps:

Quoted 7 lines

In a subsequent commit we're about to introduce a new user of the replay subsystem. With that new user, the range of commits that we'll want to replay will be identified implicitly via a single commit, and will include all descendants of that commit to any branch. If that commit has no descendants (because it's the tip of some branch), then the range of revisions that we're asked to replay becomes empty. This case does not make sense with git-replay(1), but with the new command it will.

That reads better indeed, thanks!

Patrick

#336 lore raw

PATCH v10 5/8 replay: support updating detached HEAD

In reply to Patrick Steinhardt

In a subsequent commit we're about to introduce a new git-history(1) command, which will by default work on all local branches and HEAD. This is already well-supported by the replay machinery for most of the part:
updating branches is one of its prime use cases, and the HEAD ref is also updated in case it points to any of the branches.

However, what's not supported yet is to update HEAD in case it is not a symbolic ref. We determine the refs that need to be updated by iterating through the decorations of the original commit, but we only update those refs that are DECORATION_REF_LOCAL, which covers local branches.

Address this gap by also handling DECORATION_REF_HEAD. Note though that this needs to only happen in case we're working on a detached HEAD. If HEAD is pointing to a branch, then we'd already update that branch via DECORATION_REF_LOCAL.

Refactor the loop that iterates through the decorations a bit to make the individual conditions easier to understand.

---
 replay.c                 | 47 +++++++++++++++++++++++++++++++++--------------
 t/t3650-replay-basics.sh |  9 +++++++++
 2 files changed, 42 insertions(+), 14 deletions(-)
replay.c +33 -14
index a8e6d5b30b..6a8cd2f72d 100644
@@ -150,11 +150,17 @@ static void get_ref_information(struct repository *repo,
 static void set_up_replay_mode(struct repository *repo,
 			       struct rev_cmdline_info *cmd_info,
 			       const char *onto_name,
+			       bool *detached_head,
 			       char **advance_name,
 			       struct commit **onto,
 			       struct strset **update_refs)
 {
 	struct ref_info rinfo;
+	int head_flags = 0;
+
+	refs_read_ref_full(get_main_ref_store(repo), "HEAD",
+			   RESOLVE_REF_NO_RECURSE, NULL, &head_flags);
+	*detached_head = !(head_flags & REF_ISSYMREF);
 
 	get_ref_information(repo, cmd_info, &rinfo);
 	if (!rinfo.positive_refexprs)
@@ -269,12 +275,13 @@ int replay_revisions(struct rev_info *revs,
 	struct merge_result result = {
 		.clean = 1,
 	};
+	bool detached_head;
 	char *advance;
 	int ret;
 
 	advance = xstrdup_or_null(opts->advance);
-	set_up_replay_mode(revs->repo, &revs->cmdline, opts->onto, &advance,
-			   &onto, &update_refs);
+	set_up_replay_mode(revs->repo, &revs->cmdline, opts->onto,
+			   &detached_head, &advance, &onto, &update_refs);
 
 	/* FIXME: Should allow replaying commits with the first as a root commit */
 
@@ -312,18 +319,30 @@ int replay_revisions(struct rev_info *revs,
 		/* Update any necessary branches */
 		if (advance)
 			continue;
-		decoration = get_name_decoration(&commit->object);
-		if (!decoration)
-			continue;
-		while (decoration) {
-			if (decoration->type == DECORATION_REF_LOCAL &&
-			    (opts->contained || strset_contains(update_refs,
-								decoration->name))) {
-				replay_result_queue_update(out, decoration->name,
-							   &commit->object.oid,
-							   &last_commit->object.oid);
-			}
-			decoration = decoration->next;
+
+		for (decoration = get_name_decoration(&commit->object);
+		     decoration;
+		     decoration = decoration->next)
+		{
+			if (decoration->type != DECORATION_REF_LOCAL &&
+			    decoration->type != DECORATION_REF_HEAD)
+				continue;
+
+			/*
+			 * We only need to update HEAD separately in case it's
+			 * detached. If it's not we'd already update the branch
+			 * it is pointing to.
+			 */
+			if (decoration->type == DECORATION_REF_HEAD && !detached_head)
+				continue;
+
+			if (!opts->contained &&
+			    !strset_contains(update_refs, decoration->name))
+				continue;
+
+			replay_result_queue_update(out, decoration->name,
+						   &commit->object.oid,
+						   &last_commit->object.oid);
 		}
 	}
 
t/t3650-replay-basics.sh +9 -0
index 307101eeb9..c862aa39f3 100755
@@ -249,6 +249,15 @@ test_expect_success 'using replay on bare repo to rebase multiple divergent bran
 	done
 '
 
+test_expect_success 'using replay to update detached HEAD' '
+	current_head=$(git branch --show-current) &&
+	test_when_finished git switch "$current_head" &&
+	git switch --detach &&
+	test_commit something &&
+	git replay --ref-action=print --onto HEAD~2 --ref-action=print HEAD~..HEAD >updates &&
+	test_grep "update HEAD " updates
+'
+
 test_expect_success 'merge.directoryRenames=false' '
 	# create a test case that stress-tests the rename caching
 	git switch -c rename-onto &&
Signature · 1 line
2.52.0.590.g1f87b77810.dirty
#337 lore raw

Re: [PATCH v10 5/8] replay: support updating detached HEAD

On Mon, Jan 12, 2026 at 6:17 AM Patrick Steinhardt <[email protected]> wrote:
[...]

replay.c static void get_ref_information(struct repository *repo, · line 163

Quoted 3 lines
replay.c +3 -0
+       refs_read_ref_full(get_main_ref_store(repo), "HEAD",
+                          RESOLVE_REF_NO_RECURSE, NULL, &head_flags);
+       *detached_head = !(head_flags & REF_ISSYMREF);

Ah, I like this simpler way to determine if we have a detached HEAD. Out of curiosity, though, is there a need to specify RESOLVE_REF_NO_RECURSE? I waffled on that for a bit and just left it out.

Quoted 1 line
(quoted diff) +0 -0
@@ -312,18 +319,30 @@ int replay_revisions(struct rev_info *revs,

[...]

Quoted 9 lines
replay.c +9 -0
+               for (decoration = get_name_decoration(&commit->object);
+                    decoration;
+                    decoration = decoration->next)
+               {
+                       if (decoration->type != DECORATION_REF_LOCAL &&
+                           decoration->type != DECORATION_REF_HEAD)
+                               continue;
+
+                       /*

replay.c int replay_revisions(struct rev_info *revs, · line 341

Quoted 10 lines
replay.c +10 -0
+                        * We only need to update HEAD separately in case it's
+                        * detached. If it's not we'd already update the branch
+                        * it is pointing to.
+                        */
+                       if (decoration->type == DECORATION_REF_HEAD && !detached_head)
+                               continue;
+
+                       if (!opts->contained &&
+                           !strset_contains(update_refs, decoration->name))
+                               continue;

I like this refactoring to make the conditions clearer; very nice.

Quoted 22 lines
t/t3650-replay-basics.sh +9 -1
index 307101eeb9..c862aa39f3 100755
@@ -249,6 +249,15 @@ test_expect_success 'using replay on bare repo to rebase multiple divergent bran
        done
 '
 
+test_expect_success 'using replay to update detached HEAD' '
+       current_head=$(git branch --show-current) &&
+       test_when_finished git switch "$current_head" &&
+       git switch --detach &&
+       test_commit something &&
+       git replay --ref-action=print --onto HEAD~2 --ref-action=print HEAD~..HEAD >updates &&
+       test_grep "update HEAD " updates
+'
+
 test_expect_success 'merge.directoryRenames=false' '
        # create a test case that stress-tests the rename caching
        git switch -c rename-onto &&
 
--
Quoted 1 line

2.52.0.590.g1f87b77810.dirty

Good extra test too.

#338 lore raw

Re: [PATCH v10 5/8] replay: support updating detached HEAD

Quoted 10 lines · Elijah Newren

On Mon, Jan 12, 2026 at 6:17 AM Patrick Steinhardt <[email protected]> wrote:
[...]

replay.c static void get_ref_information(struct repository *repo, · line 163

Quoted 3 lines
replay.c +3 -0
+       refs_read_ref_full(get_main_ref_store(repo), "HEAD",
+                          RESOLVE_REF_NO_RECURSE, NULL, &head_flags);
+       *detached_head = !(head_flags & REF_ISSYMREF);

Ah, I like this simpler way to determine if we have a detached HEAD. Out of curiosity, though, is there a need to specify RESOLVE_REF_NO_RECURSE? I waffled on that for a bit and just left it out.

There isn't, but I felt like it clarifies that we really only care about the immediate ref's value. It's also more efficient, even though that does not matter at all in the grand scheme of things.

Patrick

#339 lore raw

PATCH v10 6/8 wt-status: provide function to expose status for trees

In reply to Patrick Steinhardt

The "wt-status" subsystem is responsible for printing status information around the current state of the working tree. This most importantly includes information around whether the working tree or the index have any changes.

We're about to introduce a new command where the changes in neither of them are actually relevant to us. Instead, what we want is to format the changes between two different trees. While it is a little bit of a stretch to add this as functionality to _working tree_ status, it doesn't make any sense to open-code this functionality, either.

Implement a new function wt_status_collect_changes_trees() that diffs two trees and formats the status accordingly. This function is not yet used, but will be in a subsequent commit.

---
 wt-status.c | 24 ++++++++++++++++++++++++
 wt-status.h |  9 +++++++++
 2 files changed, 33 insertions(+)
wt-status.c +24 -0
index e12adb26b9..95942399f8 100644
@@ -612,6 +612,30 @@ static void wt_status_collect_updated_cb(struct diff_queue_struct *q,
 	}
 }
 
+void wt_status_collect_changes_trees(struct wt_status *s,
+				     const struct object_id *old_treeish,
+				     const struct object_id *new_treeish)
+{
+	struct diff_options opts = { 0 };
+
+	repo_diff_setup(s->repo, &opts);
+	opts.output_format = DIFF_FORMAT_CALLBACK;
+	opts.format_callback = wt_status_collect_updated_cb;
+	opts.format_callback_data = s;
+	opts.detect_rename = s->detect_rename >= 0 ? s->detect_rename : opts.detect_rename;
+	opts.rename_limit = s->rename_limit >= 0 ? s->rename_limit : opts.rename_limit;
+	opts.rename_score = s->rename_score >= 0 ? s->rename_score : opts.rename_score;
+	opts.flags.recursive = 1;
+	diff_setup_done(&opts);
+
+	diff_tree_oid(old_treeish, new_treeish, "", &opts);
+	diffcore_std(&opts);
+	diff_flush(&opts);
+	wt_status_get_state(s->repo, &s->state, 0);
+
+	diff_free(&opts);
+}
+
 static void wt_status_collect_changes_worktree(struct wt_status *s)
 {
 	struct rev_info rev;
wt-status.h +9 -0
index e40a27214a..e9fe32e98c 100644
@@ -153,6 +153,15 @@ void wt_status_add_cut_line(struct wt_status *s);
 void wt_status_prepare(struct repository *r, struct wt_status *s);
 void wt_status_print(struct wt_status *s);
 void wt_status_collect(struct wt_status *s);
+
+/*
+ * Collect all changes between the two trees. Changes will be displayed as if
+ * they were staged into the index.
+ */
+void wt_status_collect_changes_trees(struct wt_status *s,
+				     const struct object_id *old_treeish,
+				     const struct object_id *new_treeish);
+
 /*
  * Frees the buffers allocated by wt_status_collect.
  */
Signature · 1 line
2.52.0.590.g1f87b77810.dirty
#340 lore raw

PATCH v10 7/8 builtin: add new "history" command

In reply to Patrick Steinhardt

When rewriting history via git-rebase(1) there are a few very common use cases:

- The ordering of two commits should be reversed.

- A commit should be split up into two commits.

- A commit should be dropped from the history completely.

- Multiple commits should be squashed into one.

- Editing an existing commit that is not the tip of the current branch.

While these operations are all doable, it often feels needlessly kludgey to do so by doing an interactive rebase, using the editor to say what one wants, and then perform the actions. Also, some operations like splitting up a commit into two are way more involved than that and require a whole series of commands.

Rebases also do not update dependent branches. The use of stacked branches has grown quite common with competing version control systems like Jujutsu though, so it clearly is a need that users have. While rebases _can_ serve this use case if one always works on the latest stacked branch, it is somewhat awkward and very easy to get wrong.

Add a new "history" command to plug these gaps. This command will have several different subcommands to imperatively rewrite history for common use cases like the above.

---
 .gitignore                     |  1 +
 Documentation/git-history.adoc | 57 ++++++++++++++++++++++++++++++++++++++++++
 Documentation/meson.build      |  1 +
 Makefile                       |  1 +
 builtin.h                      |  1 +
 builtin/history.c              | 22 ++++++++++++++++
 command-list.txt               |  1 +
 git.c                          |  1 +
 meson.build                    |  1 +
 t/meson.build                  |  1 +
 t/t3450-history.sh             | 17 +++++++++++++
 11 files changed, 104 insertions(+)
.gitignore +1 -0
index 78a45cb5be..24635cf2d6 100644
@@ -79,6 +79,7 @@
 /git-grep
 /git-hash-object
 /git-help
+/git-history
 /git-hook
 /git-http-backend
 /git-http-fetch
Documentation/git-history.adoc new file +57 -0

57 lines not on this page · raw message

Documentation/meson.build +1 -0
index f02dbc20cb..fd2e8cc02d 100644
@@ -64,6 +64,7 @@ manpages = {
   'git-gui.adoc' : 1,
   'git-hash-object.adoc' : 1,
   'git-help.adoc' : 1,
+  'git-history.adoc' : 1,
   'git-hook.adoc' : 1,
   'git-http-backend.adoc' : 1,
   'git-http-fetch.adoc' : 1,
Makefile +1 -0
index 1c64a5d2ae..c0569ed8e4 100644
@@ -1418,6 +1418,7 @@ BUILTIN_OBJS += builtin/get-tar-commit-id.o
 BUILTIN_OBJS += builtin/grep.o
 BUILTIN_OBJS += builtin/hash-object.o
 BUILTIN_OBJS += builtin/help.o
+BUILTIN_OBJS += builtin/history.o
 BUILTIN_OBJS += builtin/hook.o
 BUILTIN_OBJS += builtin/index-pack.o
 BUILTIN_OBJS += builtin/init-db.o
builtin.h +1 -0
index 1b35565fbd..93c91d07d4 100644
@@ -172,6 +172,7 @@ int cmd_get_tar_commit_id(int argc, const char **argv, const char *prefix, struc
 int cmd_grep(int argc, const char **argv, const char *prefix, struct repository *repo);
 int cmd_hash_object(int argc, const char **argv, const char *prefix, struct repository *repo);
 int cmd_help(int argc, const char **argv, const char *prefix, struct repository *repo);
+int cmd_history(int argc, const char **argv, const char *prefix, struct repository *repo);
 int cmd_hook(int argc, const char **argv, const char *prefix, struct repository *repo);
 int cmd_index_pack(int argc, const char **argv, const char *prefix, struct repository *repo);
 int cmd_init_db(int argc, const char **argv, const char *prefix, struct repository *repo);
builtin/history.c new file +22 -0
new file mode 100644
index 0000000000..f6fe32610b
@@ -0,0 +1,22 @@
+#include "builtin.h"
+#include "gettext.h"
+#include "parse-options.h"
+
+int cmd_history(int argc,
+		const char **argv,
+		const char *prefix,
+		struct repository *repo UNUSED)
+{
+	const char * const usage[] = {
+		N_("git history [<options>]"),
+		NULL,
+	};
+	struct option options[] = {
+		OPT_END(),
+	};
+
+	argc = parse_options(argc, argv, prefix, options, usage, 0);
+	if (argc)
+		usagef("unrecognized argument: %s", argv[0]);
+	return 0;
+}
command-list.txt +1 -0
index accd3d0c4b..f9005cf459 100644
@@ -115,6 +115,7 @@ git-grep                                mainporcelain           info
 git-gui                                 mainporcelain
 git-hash-object                         plumbingmanipulators
 git-help                                ancillaryinterrogators          complete
+git-history                             mainporcelain           history
 git-hook                                purehelpers
 git-http-backend                        synchingrepositories
 git-http-fetch                          synchelpers
git.c +1 -0
index c5fad56813..744cb6527e 100644
@@ -586,6 +586,7 @@ static struct cmd_struct commands[] = {
 	{ "grep", cmd_grep, RUN_SETUP_GENTLY },
 	{ "hash-object", cmd_hash_object },
 	{ "help", cmd_help },
+	{ "history", cmd_history, RUN_SETUP },
 	{ "hook", cmd_hook, RUN_SETUP },
 	{ "index-pack", cmd_index_pack, RUN_SETUP_GENTLY | NO_PARSEOPT },
 	{ "init", cmd_init_db },
meson.build +1 -0
index a5a4e99b25..3a1d12caa4 100644
@@ -610,6 +610,7 @@ builtin_sources = [
   'builtin/grep.c',
   'builtin/hash-object.c',
   'builtin/help.c',
+  'builtin/history.c',
   'builtin/hook.c',
   'builtin/index-pack.c',
   'builtin/init-db.c',
t/meson.build +1 -0
index 459c52a489..73006b095a 100644
@@ -387,6 +387,7 @@ integration_tests = [
   't3436-rebase-more-options.sh',
   't3437-rebase-fixup-options.sh',
   't3438-rebase-broken-files.sh',
+  't3450-history.sh',
   't3500-cherry.sh',
   't3501-revert-cherry-pick.sh',
   't3502-cherry-pick-merge.sh',
t/t3450-history.sh new file +17 -0
new file mode 100755
index 0000000000..417c343d43
@@ -0,0 +1,17 @@
+#!/bin/sh
+
+test_description='tests for git-history command'
+
+. ./test-lib.sh
+
+test_expect_success 'does nothing without any arguments' '
+	git history >out 2>&1 &&
+	test_must_be_empty out
+'
+
+test_expect_success 'raises an error with unknown argument' '
+	test_must_fail git history garbage 2>err &&
+	test_grep "unrecognized argument: garbage" err
+'
+
+test_done
Signature · 1 line
2.52.0.590.g1f87b77810.dirty
#341 lore raw

PATCH v10 8/8 builtin/history: implement "reword" subcommand

In reply to Patrick Steinhardt

Implement a new "reword" subcommand for git-history(1). This subcommand is similar to the user performing an interactive rebase with a single commit changed to use the "reword" instruction.

The "reword" subcommand is built on top of the replay subsystem instead of the sequencer. This leads to some major differences compared to git-rebase(1):

- We do not check out the commit that is to be reworded and instead perform the operation in-memory. This has the obvious benefit of being significantly faster compared to git-rebase(1), but even more importantly it allows the user to rewrite history even if there are local changes in the working tree or in the index.

- We do not execute any hooks, even though we leave some room for changing this in the future.

- By default, all local branches that contain the commit will be rewritten. This especially helps with workflows that use stacked branches.

---
 Documentation/git-history.adoc |  20 +-
 builtin/history.c              | 415 ++++++++++++++++++++++++++++++++++++++++-
 t/meson.build                  |   1 +
 t/t3450-history.sh             |   6 +-
 t/t3451-history-reword.sh      | 391 ++++++++++++++++++++++++++++++++++++++
 5 files changed, 823 insertions(+), 10 deletions(-)
Documentation/git-history.adoc +18 -2
index 68c35f36b9..154e262b76 100644
@@ -8,7 +8,7 @@ git-history - EXPERIMENTAL: Rewrite history
 SYNOPSIS
 --------
 [synopsis]
-git history [<options>]
+git history reword <commit> [--ref-action=(branches|head|print)]
 
 DESCRIPTION
 -----------
@@ -50,7 +50,23 @@ first-class conflicts.
 COMMANDS
 --------
 
-No commands are supported yet.
+The following commands are available to rewrite history in different ways:
+
+`reword <commit>`::
+	Rewrite the commit message of the specified commit. All the other
+	details of this commit remain unchanged. This command will spawn an
+	editor with the current message of that commit.
+
+OPTIONS
+-------
+
+`--ref-action=(branches|head|print)`::
+	Control which references will be updated by the command, if any. With
+	`branches`, all local branches that point to commits which are
+	descendants of the original commit will be rewritten. With `head`, only
+	the current `HEAD` reference will be rewritten. With `print`, all
+	updates as they would be performed with `branches` are printed in a
+	format that can be consumed by linkgit:git-update-ref[1].
 
 GIT
 ---
builtin/history.c +410 -5

432 lines not on this page · raw message

t/meson.build +1 -0
index 73006b095a..c9f92450dc 100644
@@ -388,6 +388,7 @@ integration_tests = [
   't3437-rebase-fixup-options.sh',
   't3438-rebase-broken-files.sh',
   't3450-history.sh',
+  't3451-history-reword.sh',
   't3500-cherry.sh',
   't3501-revert-cherry-pick.sh',
   't3502-cherry-pick-merge.sh',
t/t3450-history.sh +3 -3
index 417c343d43..f513463b92 100755
@@ -5,13 +5,13 @@ test_description='tests for git-history command'
 . ./test-lib.sh
 
 test_expect_success 'does nothing without any arguments' '
-	git history >out 2>&1 &&
-	test_must_be_empty out
+	test_must_fail git history 2>err &&
+	test_grep "need a subcommand" err
 '
 
 test_expect_success 'raises an error with unknown argument' '
 	test_must_fail git history garbage 2>err &&
-	test_grep "unrecognized argument: garbage" err
+	test_grep "unknown subcommand: .garbage." err
 '
 
 test_done
t/t3451-history-reword.sh new file +391 -0

391 lines not on this page · raw message

Signature · 1 line
2.52.0.590.g1f87b77810.dirty
#342 lore raw

Re: [PATCH v10 8/8] builtin/history: implement "reword" subcommand

Quoted 18 lines · Patrick Steinhardt

Implement a new "reword" subcommand for git-history(1). This subcommand is similar to the user performing an interactive rebase with a single commit changed to use the "reword" instruction.

The "reword" subcommand is built on top of the replay subsystem instead of the sequencer. This leads to some major differences compared to git-rebase(1):

- We do not check out the commit that is to be reworded and instead perform the operation in-memory. This has the obvious benefit of being significantly faster compared to git-rebase(1), but even more importantly it allows the user to rewrite history even if there are local changes in the working tree or in the index.

- We do not execute any hooks, even though we leave some room for changing this in the future.

Quoted 6 lines

- By default, all local branches that contain the commit will be rewritten. This especially helps with workflows that use stacked branches.

This patch is now a mixture of my patch and yours; all the changes since your v9 & my patch look good to me.

#343 lore raw
In reply to Patrick Steinhardt

On Mon, Jan 12, 2026 at 6:17 AM Patrick Steinhardt <[email protected]> wrote:
[...]

Quoted 5 lines

Changes in v10:
- Split out changes that make replay_revisions() handle empty revision ranges properly.
- Drop redundant struct repository parameter in

    `replay_revisions()`.
Quoted 9 lines

- Move around die_for_incompatible_opt2().
- Fix up some of the headers in "replay.c".
- Split out the changes that make replay_revisions() handle empty
revision ranges properly.
- Create a separate commit that fixes updating detached HEAD.
- Strip "encoding" header as we're reencoding commit messages.
- Merge the logic to update refs in in REF_ACTION_HEAD and REF_ACTION_BRANCHES modes.
- Link to v9: https://lore.kernel.org/r/[email protected]

Both Junio and I highlighted some changes in patch 1 (you already indicated your agreement with Junio), and I had some minor rewording suggestions for the commit message of patch 4. All other patches in v10 look good to me.

#344 lore raw

v11 cover Introduce git-history(1) command for easy history editing

In reply to Patrick Steinhardt

Hi,

over recent months I've been playing around with Jujutsu quite frequently. While I still prefer using Git, there's been a couple features in it that I really like and that I'd like to have in Git, as well.

A copule of these features relate to history editing. Most importantly, I really dig the following commands:

- jj-abandon(1) to drop a specific commit from your history.

- jj-absorb(1) to take some changes and automatically apply them to commits in your history that last modified the respective hunks.

- jj-split(1) to split a commit into two.

- jj-new(1) to insert a new commit after or before a specific other commit.

Not all of these commands can be ported directly into Git. jj-new(1) for example doesn't really make a ton of sense for us, I'd claim. But some of these commands _do_ make sense.

This patch series is a starting point for such a command. For now, it only implements rewording of commits. I'll continue introducing new commands once this patch series has been merged though.

Changes in v11:
- Fix overly clever BUG() condition.
- Drop the struct replay_result::merge_conflict field.
- Return a positive value from replay_revisions() in case there was
a conflict.
- Improve a commit message.
- Fix check for whether setup_revisions_from_strvec() was
successful.
- Link to v10: https://lore.kernel.org/r/[email protected]

Changes in v10:
- Split out changes that make replay_revisions() handle empty revision ranges properly.
- Drop redundant struct repository parameter in

    `replay_revisions()`.

- Move around die_for_incompatible_opt2().
- Fix up some of the headers in "replay.c".
- Split out the changes that make replay_revisions() handle empty
revision ranges properly.
- Create a separate commit that fixes updating detached HEAD.
- Strip "encoding" header as we're reencoding commit messages.
- Merge the logic to update refs in in REF_ACTION_HEAD and REF_ACTION_BRANCHES modes.
- Link to v9: https://lore.kernel.org/r/[email protected]

Changes in v9:
- Rename struct replay_ref_updates to struct replay_result to make
its semantics less focussed on ref updates, only.
- Clarify and fix return codes of git-replay(1) so that we return 1 on
conflict, 128 on an error and 0 on success.
- The usual small improvements to commit messages.
- Link to v8: https://lore.kernel.org/r/[email protected]

Changes in v8:
- The series is now built on top of e0bfec3dfc (The 15th batch,
2026-01-06) with kh/replay-invalid-onto-advance at 56b77a687e
(t3650: add more regression tests for failure conditions,
2026-01-05) merged into it. The latter is expected to hit 'next'
soonish.
- Another biggish revamp to build almost completely on top of the
git-replay(1) logic.
- We now advance all branches descending from the rewritten commit by
default.
- I've dropped the patches introducing git history split and will
send this as a follow-up patch series once this once has been
merged. This was done to focus attention on the underlying mechanics
as much as possible (and to keep my own sanity with the frequent
revamps).
- Link to v7: https://lore.kernel.org/r/[email protected]

Changes in v7:
- I've rebased the patch series on top of f0ef5b6d9b (The fifth batch,

    2025-11-30) with pw/replay-exclude-gpgsig-fix at 9f3a115087 (replay:
    do not copy "gpgsign-sha256" header, 2025-11-26) merged into it to
    fix some conflicts.

- I refactored a bunch of code to be shared between split and reword.
- I am now using "--ancestry-path" and "--reverse" to enumerate
commits.
- git history split now asks for commit messages for both commits.
- git history split no longer allows the user to edit hunks so that
conflicts become impossible. This may be reintroduced at a later
point in time.
- A bunch of test improvements.
- Several commit message and documentation improvements.
- Link to v6: https://lore.kernel.org/r/[email protected]

Changes in v6:
- I've rebased the patch series again to pull in the latest updates from sa/replay-atomic-ref-updates and fix conflicts. It is now based on 4e98b730f1 (The twenty-fourth batch, 2025-10-24) with ab661bb1bb (replay: add replay.refAction config option, 2025-10-23) merged into it.
- I've dropped the "-m" options for now, so commit messages are always asked for via the editor. These can be introduced in a subsequent patch series once discussion around them has settled.
- We don't use the merge machinery anymore to pick the commits.
- Drop the commit to parse commits in the replay machinery. It didn't seem to be necessary in v5 anymore, and now that we don't use the merge machinery at all we don't ever take that code path in the first place.
- Link to v5:

    https://lore.kernel.org/r/[email protected]

Changes in v5:
- I've changed the patch series to be based on top of 133d151831 (The twenty-first batch, 2025-10-20) with sa/replay-atomic-ref-updates at a1c22e627e (SQAUASH??? t0450 band-aid, 2025-10-14) merged into it.
This is one the one hand to fix a conflict, but also to get some of
the CI updates to make GitLab CI work again.
- Some slight commit message improvements.
- Deduplicate subcommand usage strings by using defines.
- Fix the desendancy checks to properly verify that HEAD is a
descendant of the commit to be rewritten. Also add some tests for
this.
- Fix the hint that mentions that lines starting with the comment
character will be tripped after having written the commit message.
- Move an include to the correct commit.
- Link to v4: https://lore.kernel.org/r/[email protected]

Changes in v4:
- I've rebuilt the patch series. It is now based on 821f583da6 (The
thirteenth batcn, 2025-09-29) with sa/replay-atomic-ref-updates
at 665c66a743 (replay: make atomic ref updates the default behavior, 2025-09-27) merged into it. This should fix all conflicts with seen.
- I've reworked this patch series to use the same infra as
git-replay(1), as discussed during the Contributor's Summit.
- I've slimmed down the patch series to only tackle those commands
that cannot result in a conflict to keep it simple. I also learned
that Elijah has been working on a "git replay edit" command, so I
dropped that command so that we can instead use his version.
- During the Contributor's Summit we have agreed that for now, we
won't care about hook execution just yet. This may be backfilled at
a later point in time.
- I dropped "commit.verbose" handling for now, as my understanding of
it was wrong at first. This is something we should backfill.
- Link to v3: https://lore.kernel.org/r/[email protected]

Changes in v3:
- Add logic to drive the "post-rewrite" hook and add tests to verify
that all hooks are executed as expected.
- Deduplicate logic to turn a replay action into a todo command.
- Move the addition of tests for the top-level git-history(1) command
to the correct commit.
- Some smaller commit message fixes.
- Honor "commit.verbose".
- Fix copy-paste error with an error message.
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- Add a new "reword" subcommand.
- List git-history(1) in "command-list.txt".
- Add some missing error handling.
- Simplify calling convention of apply_commits() to handle root
commits internally instead of requiring every caller to do so.
- Add tests to verify that git-history(1) refuses to work with changes
in the worktree or index.
- Mark git-history(1) as experimental.
- Introduce commands to manage interrupted history edits.
- A bunch of improvements to the manpage.
- Link to v1: https://lore.kernel.org/r/[email protected]

Thanks!

Patrick

---
Patrick Steinhardt (8):
builtin/replay: extract core logic to replay revisions builtin/replay: move core logic into "libgit.a"
replay: small set of cleanups
replay: support empty commit ranges
replay: support updating detached HEAD
wt-status: provide function to expose status for trees
builtin: add new "history" command builtin/history: implement "reword" subcommand

 .gitignore                     |   1 +
 Documentation/git-history.adoc |  73 +++++++
 Documentation/meson.build      |   1 +
 Makefile                       |   2 +
 builtin.h                      |   1 +
 builtin/history.c              | 427 +++++++++++++++++++++++++++++++++++++++++
 builtin/replay.c               | 373 +++--------------------------------
 command-list.txt               |   1 +
 git.c                          |   1 +
 meson.build                    |   2 +
 replay.c                       | 371 +++++++++++++++++++++++++++++++++++
 replay.h                       |  61 ++++++
 t/meson.build                  |   2 +
 t/t3450-history.sh             |  17 ++
 t/t3451-history-reword.sh      | 391 +++++++++++++++++++++++++++++++++++++
 t/t3650-replay-basics.sh       |   9 +
 wt-status.c                    |  24 +++
 wt-status.h                    |   9 +
 18 files changed, 1425 insertions(+), 341 deletions(-)

Range-diff versus v10:

1: f02aa5abd1 ! 1: bdefcad12d builtin/replay: extract core logic to replay revisions

    @@ builtin/replay.c: static void set_up_replay_mode(struct repository *repo,
      
     -	die_for_incompatible_opt2(!!onto_name, "--onto",
     -				  !!*advance_name, "--advance");
    -+	if (!(!!onto_name ^ !!*advance_name))
    -+		BUG("expected either onto_name or *advance_name in this function");
    ++	if (!onto_name == !*advance_name)
    ++		BUG("one and only one of onto_name and *advance_name must be given");
     +
      	if (onto_name) {
      		*onto = peel_committish(repo, onto_name, "--onto");
    @@ builtin/replay.c: static struct commit *pick_regular_commit(struct repository *r
     +		struct object_id new_oid;
     +	} *updates;
     +	size_t updates_nr, updates_alloc;
    -+
    -+	bool merge_conflict;
     +};
     +
     +static void replay_result_release(struct replay_result *result)
    @@ builtin/replay.c: static struct commit *pick_regular_commit(struct repository *r
     +	}
     +
     +	if (!result.clean) {
    -+		out->merge_conflict = true;
    -+		ret = -1;
    ++		ret = 1;
     +		goto out;
     +	}
     +
    @@ builtin/replay.c: int cmd_replay(int argc,
     -		free(update_refs);
     -	}
     -	ret = result.clean;
    --
    ++	ret = 0;
    + 
      cleanup:
      	if (transaction)
      		ref_transaction_free(transaction);
    @@ builtin/replay.c: int cmd_replay(int argc,
      	release_revisions(&revs);
     -	free(advance_name);
      
    --	/* Return */
    --	if (ret < 0)
    --		exit(128);
    + 	/* Return */
    + 	if (ret < 0)
    + 		exit(128);
     -	return ret ? 0 : 1;
    -+	if (ret) {
    -+		if (result.merge_conflict)
    -+			return 1;
    -+		return 128;
    -+	}
    -+
    -+	return 0;
    ++	return ret;
      }
2:  078d713391 ! 2:  80eaf3f9fd builtin/replay: move core logic into "libgit.a"
    @@ builtin/replay.c
     -	if (!rinfo.positive_refexprs)
     -		die(_("need some commits to replay"));
     -
    --	if (!(!!onto_name ^ !!*advance_name))
    --		BUG("expected either onto_name or *advance_name in this function");
    +-	if (!onto_name == !*advance_name)
    +-		BUG("one and only one of onto_name and *advance_name must be given");
     -
     -	if (onto_name) {
     -		*onto = peel_committish(repo, onto_name, "--onto");
    @@ builtin/replay.c
     -		struct object_id new_oid;
     -	} *updates;
     -	size_t updates_nr, updates_alloc;
    --
    --	bool merge_conflict;
     -};
     -
     -static void replay_result_release(struct replay_result *result)
    @@ builtin/replay.c
     -	}
     -
     -	if (!result.clean) {
    --		out->merge_conflict = true;
    --		ret = -1;
    +-		ret = 1;
     -		goto out;
     -	}
     -
    @@ replay.c (new)
     +	if (!rinfo.positive_refexprs)
     +		die(_("need some commits to replay"));
     +
    -+	if (!(!!onto_name ^ !!*advance_name))
    -+		BUG("expected either onto_name or *advance_name in this function");
    ++	if (!onto_name == !*advance_name)
    ++		BUG("one and only one of onto_name and *advance_name must be given");
     +
     +	if (onto_name) {
     +		*onto = peel_committish(repo, onto_name, "--onto");
    @@ replay.c (new)
     +	}
     +
     +	if (!result.clean) {
    -+		out->merge_conflict = true;
    -+		ret = -1;
    ++		ret = 1;
     +		goto out;
     +	}
     +
    @@ replay.h (new)
     +		struct object_id new_oid;
     +	} *updates;
     +	size_t updates_nr, updates_alloc;
    -+
    -+	/* Set to true in case the replay failed with a merge conflict. */
    -+	bool merge_conflict;
     +};
     +
     +void replay_result_release(struct replay_result *result);
    @@ replay.h (new)
     + * index and references untouched. Reference updates caused by the replay will
     + * be recorded in the `updates` out pointer.
     + *
    -+ * Returns 0 on success, a negative error code otherwise.
    ++ * Returns 0 on success, 1 on conflict and a negative error code otherwise.
     + */
     +int replay_revisions(struct rev_info *revs,
     +		     struct replay_revisions_options *opts,
3:  44f96f6b93 = 3:  bd6783570b replay: small set of cleanups
4:  0c861b1a37 ! 4:  e927f66224 replay: support empty commit ranges

@@ Commit message

In a subsequent commit we're about to introduce a new user of the replay subsystem. With that new user, the range of commits that we'll want to
- replay will be identified implicitly via "HEAD". With such implicit
- ranges it becomes likely that the range of revisions that we're asked to
- replay becomes empty. This case does not make sense with git-replay(1),
- but with the new command it will.
+ replay will be identified implicitly via a single commit, and will
+ include all descendants of that commit to any branch. If that commit has
+ no descendants (because it's the tip of some branch), then the range of
+ revisions that we're asked to replay becomes empty. This case does not
+ make sense with git-replay(1), but with the new command it will.

This case is not currently supported by replay_revisions() though because we zero-initialize struct merge_result. This includes its

5:  03a64727ab = 5:  c8ed32bfae replay: support updating detached HEAD
6:  453a5769a6 = 6:  79f8bf7613 wt-status: provide function to expose status for trees
7:  f73ad9a468 = 7:  d0d56cc4fc builtin: add new "history" command
8:  e7af330353 ! 8:  464f5467ab builtin/history: implement "reword" subcommand
    @@ builtin/history.c
     +	}
     +
     +	setup_revisions_from_strvec(&args, &revs, NULL);
    -+	if (revs.nr)
    -+		BUG("revisions were set up with invalid argument '%s'", args.v[0]);
    ++	if (args.nr != 1)
    ++		BUG("revisions were set up with invalid argument");
     +
     +	opts.onto = oid_to_hex_r(hex, &rewritten->object.oid);
     +

---
base-commit: 02bdc12118c43e0a65258eb742492965859bffb6
change-id: 20250819-b4-pks-history-builtin-83398f9a05f0

#345 lore raw

PATCH v11 1/8 builtin/replay: extract core logic to replay revisions

We're about to move the core logic used to replay revisions onto a new base into the "libgit.a" library. Prepare for this by pulling out the logic into a new function replay_revisions() that:

1. Takes a set of revisions to replay and some options that tell it how it ought to replay the revisions.

2. Replays the commits.

3. Records any reference updates that would be caused by replaying the commits in a structure that is owned by the caller.

The logic itself will be moved into a separate file in the next commit. This change is not expected to cause user-visible change in behaviour.

---
 builtin/replay.c | 269 +++++++++++++++++++++++++++++++++----------------------
 1 file changed, 162 insertions(+), 107 deletions(-)
builtin/replay.c +162 -107
index 1960bbbee8..daf907668c 100644
@@ -177,8 +177,9 @@ static void set_up_replay_mode(struct repository *repo,
 	if (!rinfo.positive_refexprs)
 		die(_("need some commits to replay"));
 
-	die_for_incompatible_opt2(!!onto_name, "--onto",
-				  !!*advance_name, "--advance");
+	if (!onto_name == !*advance_name)
+		BUG("one and only one of onto_name and *advance_name must be given");
+
 	if (onto_name) {
 		*onto = peel_committish(repo, onto_name, "--onto");
 		if (rinfo.positive_refexprs <
@@ -253,6 +254,134 @@ static struct commit *pick_regular_commit(struct repository *repo,
 	return create_commit(repo, result->tree, pickme, replayed_base);
 }
 
+struct replay_revisions_options {
+	const char *advance;
+	const char *onto;
+	int contained;
+};
+
+struct replay_result {
+	struct replay_ref_update {
+		char *refname;
+		struct object_id old_oid;
+		struct object_id new_oid;
+	} *updates;
+	size_t updates_nr, updates_alloc;
+};
+
+static void replay_result_release(struct replay_result *result)
+{
+	for (size_t i = 0; i < result->updates_nr; i++)
+		free(result->updates[i].refname);
+	free(result->updates);
+}
+
+static void replay_result_queue_update(struct replay_result *result,
+				       const char *refname,
+				       const struct object_id *old_oid,
+				       const struct object_id *new_oid)
+{
+	ALLOC_GROW(result->updates, result->updates_nr + 1, result->updates_alloc);
+	result->updates[result->updates_nr].refname = xstrdup(refname);
+	result->updates[result->updates_nr].old_oid = *old_oid;
+	result->updates[result->updates_nr].new_oid = *new_oid;
+	result->updates_nr++;
+}
+
+static int replay_revisions(struct rev_info *revs,
+			    struct replay_revisions_options *opts,
+			    struct replay_result *out)
+{
+	kh_oid_map_t *replayed_commits = NULL;
+	struct strset *update_refs = NULL;
+	struct commit *last_commit = NULL;
+	struct commit *commit;
+	struct commit *onto = NULL;
+	struct merge_options merge_opt;
+	struct merge_result result;
+	char *advance;
+	int ret;
+
+	advance = xstrdup_or_null(opts->advance);
+	set_up_replay_mode(revs->repo, &revs->cmdline, opts->onto, &advance,
+			   &onto, &update_refs);
+
+	/* FIXME: Should allow replaying commits with the first as a root commit */
+
+	if (prepare_revision_walk(revs) < 0) {
+		ret = error(_("error preparing revisions"));
+		goto out;
+	}
+
+	init_basic_merge_options(&merge_opt, revs->repo);
+	memset(&result, 0, sizeof(result));
+	merge_opt.show_rename_progress = 0;
+	last_commit = onto;
+	replayed_commits = kh_init_oid_map();
+	while ((commit = get_revision(revs))) {
+		const struct name_decoration *decoration;
+		khint_t pos;
+		int hr;
+
+		if (!commit->parents)
+			die(_("replaying down from root commit is not supported yet!"));
+		if (commit->parents->next)
+			die(_("replaying merge commits is not supported yet!"));
+
+		last_commit = pick_regular_commit(revs->repo, commit, replayed_commits,
+						  onto, &merge_opt, &result);
+		if (!last_commit)
+			break;
+
+		/* Record commit -> last_commit mapping */
+		pos = kh_put_oid_map(replayed_commits, commit->object.oid, &hr);
+		if (hr == 0)
+			BUG("Duplicate rewritten commit: %s\n",
+			    oid_to_hex(&commit->object.oid));
+		kh_value(replayed_commits, pos) = last_commit;
+
+		/* Update any necessary branches */
+		if (advance)
+			continue;
+		decoration = get_name_decoration(&commit->object);
+		if (!decoration)
+			continue;
+		while (decoration) {
+			if (decoration->type == DECORATION_REF_LOCAL &&
+			    (opts->contained || strset_contains(update_refs,
+								decoration->name))) {
+				replay_result_queue_update(out, decoration->name,
+							   &commit->object.oid,
+							   &last_commit->object.oid);
+			}
+			decoration = decoration->next;
+		}
+	}
+
+	if (!result.clean) {
+		ret = 1;
+		goto out;
+	}
+
+	/* In --advance mode, advance the target ref */
+	if (advance)
+		replay_result_queue_update(out, advance,
+					   &onto->object.oid,
+					   &last_commit->object.oid);
+
+	ret = 0;
+
+out:
+	if (update_refs) {
+		strset_clear(update_refs);
+		free(update_refs);
+	}
+	kh_destroy_oid_map(replayed_commits);
+	merge_finalize(&merge_opt, &result);
+	free(advance);
+	return ret;
+}
+
 static enum ref_action_mode parse_ref_action_mode(const char *ref_action, const char *source)
 {
 	if (!ref_action || !strcmp(ref_action, "update"))
@@ -306,21 +435,11 @@ int cmd_replay(int argc,
 	       const char *prefix,
 	       struct repository *repo)
 {
-	const char *advance_name_opt = NULL;
-	char *advance_name = NULL;
-	struct commit *onto = NULL;
-	const char *onto_name = NULL;
-	int contained = 0;
+	struct replay_revisions_options opts = { 0 };
+	struct replay_result result = { 0 };
 	const char *ref_action = NULL;
 	enum ref_action_mode ref_mode;
-
 	struct rev_info revs;
-	struct commit *last_commit = NULL;
-	struct commit *commit;
-	struct merge_options merge_opt;
-	struct merge_result result;
-	struct strset *update_refs = NULL;
-	kh_oid_map_t *replayed_commits;
 	struct ref_transaction *transaction = NULL;
 	struct strbuf transaction_err = STRBUF_INIT;
 	struct strbuf reflog_msg = STRBUF_INIT;
@@ -333,13 +452,13 @@ int cmd_replay(int argc,
 		NULL
 	};
 	struct option replay_options[] = {
-		OPT_STRING(0, "advance", &advance_name_opt,
+		OPT_STRING(0, "advance", &opts.advance,
 			   N_("branch"),
 			   N_("make replay advance given branch")),
-		OPT_STRING(0, "onto", &onto_name,
+		OPT_STRING(0, "onto", &opts.onto,
 			   N_("revision"),
 			   N_("replay onto given commit")),
-		OPT_BOOL(0, "contained", &contained,
+		OPT_BOOL(0, "contained", &opts.contained,
 			 N_("update all branches that point at commits in <revision-range>")),
 		OPT_STRING(0, "ref-action", &ref_action,
 			   N_("mode"),
@@ -350,19 +469,19 @@ int cmd_replay(int argc,
 	argc = parse_options(argc, argv, prefix, replay_options, replay_usage,
 			     PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN_OPT);
 
-	if (!onto_name && !advance_name_opt) {
+	if (!opts.onto && !opts.advance) {
 		error(_("option --onto or --advance is mandatory"));
 		usage_with_options(replay_usage, replay_options);
 	}
 
-	die_for_incompatible_opt2(!!advance_name_opt, "--advance",
-				  contained, "--contained");
+	die_for_incompatible_opt2(!!opts.advance, "--advance",
+				  opts.contained, "--contained");
+	die_for_incompatible_opt2(!!opts.advance, "--advance",
+				  !!opts.onto, "--onto");
 
 	/* Parse ref action mode from command line or config */
 	ref_mode = get_ref_action_mode(repo, ref_action);
 
-	advance_name = xstrdup_or_null(advance_name_opt);
-
 	repo_init_revisions(repo, &revs, prefix);
 
 	/*
@@ -414,18 +533,19 @@ int cmd_replay(int argc,
 		revs.simplify_history = 0;
 	}
 
-	set_up_replay_mode(repo, &revs.cmdline,
-			   onto_name, &advance_name,
-			   &onto, &update_refs);
-
-	/* FIXME: Should allow replaying commits with the first as a root commit */
+	ret = replay_revisions(&revs, &opts, &result);
+	if (ret)
+		goto cleanup;
 
 	/* Build reflog message */
-	if (advance_name_opt)
-		strbuf_addf(&reflog_msg, "replay --advance %s", advance_name_opt);
-	else
-		strbuf_addf(&reflog_msg, "replay --onto %s",
-			    oid_to_hex(&onto->object.oid));
+	if (opts.advance) {
+		strbuf_addf(&reflog_msg, "replay --advance %s", opts.advance);
+	} else {
+		struct object_id oid;
+		if (repo_get_oid_committish(repo, opts.onto, &oid))
+			BUG("--onto commit should have been resolved beforehand already");
+		strbuf_addf(&reflog_msg, "replay --onto %s", oid_to_hex(&oid));
+	}
 
 	/* Initialize ref transaction if using update mode */
 	if (ref_mode == REF_ACTION_UPDATE) {
@@ -438,78 +558,19 @@ int cmd_replay(int argc,
 		}
 	}
 
-	if (prepare_revision_walk(&revs) < 0) {
-		ret = error(_("error preparing revisions"));
-		goto cleanup;
-	}
-
-	init_basic_merge_options(&merge_opt, repo);
-	memset(&result, 0, sizeof(result));
-	merge_opt.show_rename_progress = 0;
-	last_commit = onto;
-	replayed_commits = kh_init_oid_map();
-	while ((commit = get_revision(&revs))) {
-		const struct name_decoration *decoration;
-		khint_t pos;
-		int hr;
-
-		if (!commit->parents)
-			die(_("replaying down from root commit is not supported yet!"));
-		if (commit->parents->next)
-			die(_("replaying merge commits is not supported yet!"));
-
-		last_commit = pick_regular_commit(repo, commit, replayed_commits,
-						  onto, &merge_opt, &result);
-		if (!last_commit)
-			break;
-
-		/* Record commit -> last_commit mapping */
-		pos = kh_put_oid_map(replayed_commits, commit->object.oid, &hr);
-		if (hr == 0)
-			BUG("Duplicate rewritten commit: %s\n",
-			    oid_to_hex(&commit->object.oid));
-		kh_value(replayed_commits, pos) = last_commit;
-
-		/* Update any necessary branches */
-		if (advance_name)
-			continue;
-		decoration = get_name_decoration(&commit->object);
-		if (!decoration)
-			continue;
-		while (decoration) {
-			if (decoration->type == DECORATION_REF_LOCAL &&
-			    (contained || strset_contains(update_refs,
-							  decoration->name))) {
-				if (handle_ref_update(ref_mode, transaction,
-						      decoration->name,
-						      &last_commit->object.oid,
-						      &commit->object.oid,
-						      reflog_msg.buf,
-						      &transaction_err) < 0) {
-					ret = error(_("failed to update ref '%s': %s"),
-						    decoration->name, transaction_err.buf);
-					goto cleanup;
-				}
-			}
-			decoration = decoration->next;
-		}
-	}
-
-	/* In --advance mode, advance the target ref */
-	if (result.clean == 1 && advance_name) {
-		if (handle_ref_update(ref_mode, transaction, advance_name,
-				      &last_commit->object.oid,
-				      &onto->object.oid,
-				      reflog_msg.buf,
-				      &transaction_err) < 0) {
+	for (size_t i = 0; i < result.updates_nr; i++) {
+		ret = handle_ref_update(ref_mode, transaction, result.updates[i].refname,
+					&result.updates[i].new_oid, &result.updates[i].old_oid,
+					reflog_msg.buf, &transaction_err);
+		if (ret) {
 			ret = error(_("failed to update ref '%s': %s"),
-				    advance_name, transaction_err.buf);
+				    result.updates[i].refname, transaction_err.buf);
 			goto cleanup;
 		}
 	}
 
 	/* Commit the ref transaction if we have one */
-	if (transaction && result.clean == 1) {
+	if (transaction) {
 		if (ref_transaction_commit(transaction, &transaction_err)) {
 			ret = error(_("failed to commit ref transaction: %s"),
 				    transaction_err.buf);
@@ -517,24 +578,18 @@ int cmd_replay(int argc,
 		}
 	}
 
-	merge_finalize(&merge_opt, &result);
-	kh_destroy_oid_map(replayed_commits);
-	if (update_refs) {
-		strset_clear(update_refs);
-		free(update_refs);
-	}
-	ret = result.clean;
+	ret = 0;
 
 cleanup:
 	if (transaction)
 		ref_transaction_free(transaction);
+	replay_result_release(&result);
 	strbuf_release(&transaction_err);
 	strbuf_release(&reflog_msg);
 	release_revisions(&revs);
-	free(advance_name);
 
 	/* Return */
 	if (ret < 0)
 		exit(128);
-	return ret ? 0 : 1;
+	return ret;
 }
Signature · 1 line
2.52.0.590.g1f87b77810.dirty
#346 lore raw

PATCH v11 2/8 builtin/replay: move core logic into "libgit.a"

In reply to Patrick Steinhardt

Move the core logic used to replay commits into "libgit.a" so that it can be easily reused by other commands. It will be used in a subsequent commit where we're about to introduce a new git-history(1) command.

Note that with this change we have no sign-comparison warnings anymore, and neither do we depend on the_repository.

---
 Makefile         |   1 +
 builtin/replay.c | 366 +------------------------------------------------------
 meson.build      |   1 +
 replay.c         | 354 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 replay.h         |  61 ++++++++++
 5 files changed, 418 insertions(+), 365 deletions(-)
Makefile +1 -0
index b7eba509c6..1c64a5d2ae 100644
@@ -1285,6 +1285,7 @@ LIB_OBJS += repack-geometry.o
 LIB_OBJS += repack-midx.o
 LIB_OBJS += repack-promisor.o
 LIB_OBJS += replace-object.o
+LIB_OBJS += replay.o
 LIB_OBJS += repo-settings.o
 LIB_OBJS += repository.o
 LIB_OBJS += rerere.o
builtin/replay.c +1 -365

387 lines not on this page · raw message

meson.build +1 -0
index dd52efd1c8..a5a4e99b25 100644
@@ -471,6 +471,7 @@ libgit_sources = [
   'repack-midx.c',
   'repack-promisor.c',
   'replace-object.c',
+  'replay.c',
   'repo-settings.c',
   'repository.c',
   'rerere.c',
replay.c new file +354 -0

354 lines not on this page · raw message

replay.h new file +61 -0

61 lines not on this page · raw message

Signature · 1 line
2.52.0.590.g1f87b77810.dirty
#347 lore raw

PATCH v11 3/8 replay: small set of cleanups

In reply to Patrick Steinhardt

Perform a small set of cleanups so that the "replay" logic compiles with "-Wsign-compare" and doesn't use the_repository anymore. Note that there are still some implicit dependencies on the_repository, e.g. because we use get_commit_output_encoding().

---
 replay.c | 11 ++++-------
 1 file changed, 4 insertions(+), 7 deletions(-)
replay.c +4 -7
index c580a9caa2..ae13b59abc 100644
@@ -1,5 +1,4 @@
 #define USE_THE_REPOSITORY_VARIABLE
-#define DISABLE_SIGN_COMPARE_WARNINGS
 
 #include "git-compat-util.h"
 #include "environment.h"
@@ -78,7 +77,7 @@ static struct commit *create_commit(struct repository *repo,
 	obj = parse_object(repo, &ret);
 
 out:
-	repo_unuse_commit_buffer(the_repository, based_on, message);
+	repo_unuse_commit_buffer(repo, based_on, message);
 	free_commit_extra_headers(extra);
 	free_commit_list(parents);
 	strbuf_release(&msg);
@@ -90,16 +89,14 @@ struct ref_info {
 	struct commit *onto;
 	struct strset positive_refs;
 	struct strset negative_refs;
-	int positive_refexprs;
-	int negative_refexprs;
+	size_t positive_refexprs;
+	size_t negative_refexprs;
 };
 
 static void get_ref_information(struct repository *repo,
 				struct rev_cmdline_info *cmd_info,
 				struct ref_info *ref_info)
 {
-	int i;
-
 	ref_info->onto = NULL;
 	strset_init(&ref_info->positive_refs);
 	strset_init(&ref_info->negative_refs);
@@ -121,7 +118,7 @@ static void get_ref_information(struct repository *repo,
 	 * the second because they'd likely just be replaying commits on top
 	 * of the same commit and not making any difference.
 	 */
-	for (i = 0; i < cmd_info->nr; i++) {
+	for (size_t i = 0; i < cmd_info->nr; i++) {
 		struct rev_cmdline_entry *e = cmd_info->rev + i;
 		struct object_id oid;
 		const char *refexpr = e->name;
Signature · 1 line
2.52.0.590.g1f87b77810.dirty
#348 lore raw

PATCH v11 4/8 replay: support empty commit ranges

In reply to Patrick Steinhardt

In a subsequent commit we're about to introduce a new user of the replay subsystem. With that new user, the range of commits that we'll want to replay will be identified implicitly via a single commit, and will include all descendants of that commit to any branch. If that commit has no descendants (because it's the tip of some branch), then the range of revisions that we're asked to replay becomes empty. This case does not make sense with git-replay(1), but with the new command it will.

This case is not currently supported by replay_revisions() though because we zero-initialize struct merge_result. This includes its .clean member, which indicates whether the merge ran into a conflict or not. But given that we don't have any revision to replay, we won't ever perform any merge at all, and consequently that member will never be set to 1. We thus later think that there's been a merge conflict and return an error from replay_commits().

Address this issue by initializing the .clean member to 1.

---
 replay.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
replay.c +3 -2
index ae13b59abc..6680d50bd7 100644
@@ -266,7 +266,9 @@ int replay_revisions(struct rev_info *revs,
 	struct commit *commit;
 	struct commit *onto = NULL;
 	struct merge_options merge_opt;
-	struct merge_result result;
+	struct merge_result result = {
+		.clean = 1,
+	};
 	char *advance;
 	int ret;
 
@@ -282,7 +284,6 @@ int replay_revisions(struct rev_info *revs,
 	}
 
 	init_basic_merge_options(&merge_opt, revs->repo);
-	memset(&result, 0, sizeof(result));
 	merge_opt.show_rename_progress = 0;
 	last_commit = onto;
 	replayed_commits = kh_init_oid_map();
Signature · 1 line
2.52.0.590.g1f87b77810.dirty
#349 lore raw

PATCH v11 5/8 replay: support updating detached HEAD

In reply to Patrick Steinhardt

In a subsequent commit we're about to introduce a new git-history(1) command, which will by default work on all local branches and HEAD. This is already well-supported by the replay machinery for most of the part:
updating branches is one of its prime use cases, and the HEAD ref is also updated in case it points to any of the branches.

However, what's not supported yet is to update HEAD in case it is not a symbolic ref. We determine the refs that need to be updated by iterating through the decorations of the original commit, but we only update those refs that are DECORATION_REF_LOCAL, which covers local branches.

Address this gap by also handling DECORATION_REF_HEAD. Note though that this needs to only happen in case we're working on a detached HEAD. If HEAD is pointing to a branch, then we'd already update that branch via DECORATION_REF_LOCAL.

Refactor the loop that iterates through the decorations a bit to make the individual conditions easier to understand.

---
 replay.c                 | 47 +++++++++++++++++++++++++++++++++--------------
 t/t3650-replay-basics.sh |  9 +++++++++
 2 files changed, 42 insertions(+), 14 deletions(-)
replay.c +33 -14
index 6680d50bd7..94fb76384b 100644
@@ -150,11 +150,17 @@ static void get_ref_information(struct repository *repo,
 static void set_up_replay_mode(struct repository *repo,
 			       struct rev_cmdline_info *cmd_info,
 			       const char *onto_name,
+			       bool *detached_head,
 			       char **advance_name,
 			       struct commit **onto,
 			       struct strset **update_refs)
 {
 	struct ref_info rinfo;
+	int head_flags = 0;
+
+	refs_read_ref_full(get_main_ref_store(repo), "HEAD",
+			   RESOLVE_REF_NO_RECURSE, NULL, &head_flags);
+	*detached_head = !(head_flags & REF_ISSYMREF);
 
 	get_ref_information(repo, cmd_info, &rinfo);
 	if (!rinfo.positive_refexprs)
@@ -269,12 +275,13 @@ int replay_revisions(struct rev_info *revs,
 	struct merge_result result = {
 		.clean = 1,
 	};
+	bool detached_head;
 	char *advance;
 	int ret;
 
 	advance = xstrdup_or_null(opts->advance);
-	set_up_replay_mode(revs->repo, &revs->cmdline, opts->onto, &advance,
-			   &onto, &update_refs);
+	set_up_replay_mode(revs->repo, &revs->cmdline, opts->onto,
+			   &detached_head, &advance, &onto, &update_refs);
 
 	/* FIXME: Should allow replaying commits with the first as a root commit */
 
@@ -312,18 +319,30 @@ int replay_revisions(struct rev_info *revs,
 		/* Update any necessary branches */
 		if (advance)
 			continue;
-		decoration = get_name_decoration(&commit->object);
-		if (!decoration)
-			continue;
-		while (decoration) {
-			if (decoration->type == DECORATION_REF_LOCAL &&
-			    (opts->contained || strset_contains(update_refs,
-								decoration->name))) {
-				replay_result_queue_update(out, decoration->name,
-							   &commit->object.oid,
-							   &last_commit->object.oid);
-			}
-			decoration = decoration->next;
+
+		for (decoration = get_name_decoration(&commit->object);
+		     decoration;
+		     decoration = decoration->next)
+		{
+			if (decoration->type != DECORATION_REF_LOCAL &&
+			    decoration->type != DECORATION_REF_HEAD)
+				continue;
+
+			/*
+			 * We only need to update HEAD separately in case it's
+			 * detached. If it's not we'd already update the branch
+			 * it is pointing to.
+			 */
+			if (decoration->type == DECORATION_REF_HEAD && !detached_head)
+				continue;
+
+			if (!opts->contained &&
+			    !strset_contains(update_refs, decoration->name))
+				continue;
+
+			replay_result_queue_update(out, decoration->name,
+						   &commit->object.oid,
+						   &last_commit->object.oid);
 		}
 	}
 
t/t3650-replay-basics.sh +9 -0
index 307101eeb9..c862aa39f3 100755
@@ -249,6 +249,15 @@ test_expect_success 'using replay on bare repo to rebase multiple divergent bran
 	done
 '
 
+test_expect_success 'using replay to update detached HEAD' '
+	current_head=$(git branch --show-current) &&
+	test_when_finished git switch "$current_head" &&
+	git switch --detach &&
+	test_commit something &&
+	git replay --ref-action=print --onto HEAD~2 --ref-action=print HEAD~..HEAD >updates &&
+	test_grep "update HEAD " updates
+'
+
 test_expect_success 'merge.directoryRenames=false' '
 	# create a test case that stress-tests the rename caching
 	git switch -c rename-onto &&
Signature · 1 line
2.52.0.590.g1f87b77810.dirty
#350 lore raw

PATCH v11 6/8 wt-status: provide function to expose status for trees

In reply to Patrick Steinhardt

The "wt-status" subsystem is responsible for printing status information around the current state of the working tree. This most importantly includes information around whether the working tree or the index have any changes.

We're about to introduce a new command where the changes in neither of them are actually relevant to us. Instead, what we want is to format the changes between two different trees. While it is a little bit of a stretch to add this as functionality to _working tree_ status, it doesn't make any sense to open-code this functionality, either.

Implement a new function wt_status_collect_changes_trees() that diffs two trees and formats the status accordingly. This function is not yet used, but will be in a subsequent commit.

---
 wt-status.c | 24 ++++++++++++++++++++++++
 wt-status.h |  9 +++++++++
 2 files changed, 33 insertions(+)
wt-status.c +24 -0
index e12adb26b9..95942399f8 100644
@@ -612,6 +612,30 @@ static void wt_status_collect_updated_cb(struct diff_queue_struct *q,
 	}
 }
 
+void wt_status_collect_changes_trees(struct wt_status *s,
+				     const struct object_id *old_treeish,
+				     const struct object_id *new_treeish)
+{
+	struct diff_options opts = { 0 };
+
+	repo_diff_setup(s->repo, &opts);
+	opts.output_format = DIFF_FORMAT_CALLBACK;
+	opts.format_callback = wt_status_collect_updated_cb;
+	opts.format_callback_data = s;
+	opts.detect_rename = s->detect_rename >= 0 ? s->detect_rename : opts.detect_rename;
+	opts.rename_limit = s->rename_limit >= 0 ? s->rename_limit : opts.rename_limit;
+	opts.rename_score = s->rename_score >= 0 ? s->rename_score : opts.rename_score;
+	opts.flags.recursive = 1;
+	diff_setup_done(&opts);
+
+	diff_tree_oid(old_treeish, new_treeish, "", &opts);
+	diffcore_std(&opts);
+	diff_flush(&opts);
+	wt_status_get_state(s->repo, &s->state, 0);
+
+	diff_free(&opts);
+}
+
 static void wt_status_collect_changes_worktree(struct wt_status *s)
 {
 	struct rev_info rev;
wt-status.h +9 -0
index e40a27214a..e9fe32e98c 100644
@@ -153,6 +153,15 @@ void wt_status_add_cut_line(struct wt_status *s);
 void wt_status_prepare(struct repository *r, struct wt_status *s);
 void wt_status_print(struct wt_status *s);
 void wt_status_collect(struct wt_status *s);
+
+/*
+ * Collect all changes between the two trees. Changes will be displayed as if
+ * they were staged into the index.
+ */
+void wt_status_collect_changes_trees(struct wt_status *s,
+				     const struct object_id *old_treeish,
+				     const struct object_id *new_treeish);
+
 /*
  * Frees the buffers allocated by wt_status_collect.
  */
Signature · 1 line
2.52.0.590.g1f87b77810.dirty
#351 lore raw

PATCH v11 7/8 builtin: add new "history" command

In reply to Patrick Steinhardt

When rewriting history via git-rebase(1) there are a few very common use cases:

- The ordering of two commits should be reversed.

- A commit should be split up into two commits.

- A commit should be dropped from the history completely.

- Multiple commits should be squashed into one.

- Editing an existing commit that is not the tip of the current branch.

While these operations are all doable, it often feels needlessly kludgey to do so by doing an interactive rebase, using the editor to say what one wants, and then perform the actions. Also, some operations like splitting up a commit into two are way more involved than that and require a whole series of commands.

Rebases also do not update dependent branches. The use of stacked branches has grown quite common with competing version control systems like Jujutsu though, so it clearly is a need that users have. While rebases _can_ serve this use case if one always works on the latest stacked branch, it is somewhat awkward and very easy to get wrong.

Add a new "history" command to plug these gaps. This command will have several different subcommands to imperatively rewrite history for common use cases like the above.

---
 .gitignore                     |  1 +
 Documentation/git-history.adoc | 57 ++++++++++++++++++++++++++++++++++++++++++
 Documentation/meson.build      |  1 +
 Makefile                       |  1 +
 builtin.h                      |  1 +
 builtin/history.c              | 22 ++++++++++++++++
 command-list.txt               |  1 +
 git.c                          |  1 +
 meson.build                    |  1 +
 t/meson.build                  |  1 +
 t/t3450-history.sh             | 17 +++++++++++++
 11 files changed, 104 insertions(+)
.gitignore +1 -0
index 78a45cb5be..24635cf2d6 100644
@@ -79,6 +79,7 @@
 /git-grep
 /git-hash-object
 /git-help
+/git-history
 /git-hook
 /git-http-backend
 /git-http-fetch
Documentation/git-history.adoc new file +57 -0

57 lines not on this page · raw message

Documentation/meson.build +1 -0
index f02dbc20cb..fd2e8cc02d 100644
@@ -64,6 +64,7 @@ manpages = {
   'git-gui.adoc' : 1,
   'git-hash-object.adoc' : 1,
   'git-help.adoc' : 1,
+  'git-history.adoc' : 1,
   'git-hook.adoc' : 1,
   'git-http-backend.adoc' : 1,
   'git-http-fetch.adoc' : 1,
Makefile +1 -0
index 1c64a5d2ae..c0569ed8e4 100644
@@ -1418,6 +1418,7 @@ BUILTIN_OBJS += builtin/get-tar-commit-id.o
 BUILTIN_OBJS += builtin/grep.o
 BUILTIN_OBJS += builtin/hash-object.o
 BUILTIN_OBJS += builtin/help.o
+BUILTIN_OBJS += builtin/history.o
 BUILTIN_OBJS += builtin/hook.o
 BUILTIN_OBJS += builtin/index-pack.o
 BUILTIN_OBJS += builtin/init-db.o
builtin.h +1 -0
index 1b35565fbd..93c91d07d4 100644
@@ -172,6 +172,7 @@ int cmd_get_tar_commit_id(int argc, const char **argv, const char *prefix, struc
 int cmd_grep(int argc, const char **argv, const char *prefix, struct repository *repo);
 int cmd_hash_object(int argc, const char **argv, const char *prefix, struct repository *repo);
 int cmd_help(int argc, const char **argv, const char *prefix, struct repository *repo);
+int cmd_history(int argc, const char **argv, const char *prefix, struct repository *repo);
 int cmd_hook(int argc, const char **argv, const char *prefix, struct repository *repo);
 int cmd_index_pack(int argc, const char **argv, const char *prefix, struct repository *repo);
 int cmd_init_db(int argc, const char **argv, const char *prefix, struct repository *repo);
builtin/history.c new file +22 -0
new file mode 100644
index 0000000000..f6fe32610b
@@ -0,0 +1,22 @@
+#include "builtin.h"
+#include "gettext.h"
+#include "parse-options.h"
+
+int cmd_history(int argc,
+		const char **argv,
+		const char *prefix,
+		struct repository *repo UNUSED)
+{
+	const char * const usage[] = {
+		N_("git history [<options>]"),
+		NULL,
+	};
+	struct option options[] = {
+		OPT_END(),
+	};
+
+	argc = parse_options(argc, argv, prefix, options, usage, 0);
+	if (argc)
+		usagef("unrecognized argument: %s", argv[0]);
+	return 0;
+}
command-list.txt +1 -0
index accd3d0c4b..f9005cf459 100644
@@ -115,6 +115,7 @@ git-grep                                mainporcelain           info
 git-gui                                 mainporcelain
 git-hash-object                         plumbingmanipulators
 git-help                                ancillaryinterrogators          complete
+git-history                             mainporcelain           history
 git-hook                                purehelpers
 git-http-backend                        synchingrepositories
 git-http-fetch                          synchelpers
git.c +1 -0
index c5fad56813..744cb6527e 100644
@@ -586,6 +586,7 @@ static struct cmd_struct commands[] = {
 	{ "grep", cmd_grep, RUN_SETUP_GENTLY },
 	{ "hash-object", cmd_hash_object },
 	{ "help", cmd_help },
+	{ "history", cmd_history, RUN_SETUP },
 	{ "hook", cmd_hook, RUN_SETUP },
 	{ "index-pack", cmd_index_pack, RUN_SETUP_GENTLY | NO_PARSEOPT },
 	{ "init", cmd_init_db },
meson.build +1 -0
index a5a4e99b25..3a1d12caa4 100644
@@ -610,6 +610,7 @@ builtin_sources = [
   'builtin/grep.c',
   'builtin/hash-object.c',
   'builtin/help.c',
+  'builtin/history.c',
   'builtin/hook.c',
   'builtin/index-pack.c',
   'builtin/init-db.c',
t/meson.build +1 -0
index 459c52a489..73006b095a 100644
@@ -387,6 +387,7 @@ integration_tests = [
   't3436-rebase-more-options.sh',
   't3437-rebase-fixup-options.sh',
   't3438-rebase-broken-files.sh',
+  't3450-history.sh',
   't3500-cherry.sh',
   't3501-revert-cherry-pick.sh',
   't3502-cherry-pick-merge.sh',
t/t3450-history.sh new file +17 -0
new file mode 100755
index 0000000000..417c343d43
@@ -0,0 +1,17 @@
+#!/bin/sh
+
+test_description='tests for git-history command'
+
+. ./test-lib.sh
+
+test_expect_success 'does nothing without any arguments' '
+	git history >out 2>&1 &&
+	test_must_be_empty out
+'
+
+test_expect_success 'raises an error with unknown argument' '
+	test_must_fail git history garbage 2>err &&
+	test_grep "unrecognized argument: garbage" err
+'
+
+test_done
Signature · 1 line
2.52.0.590.g1f87b77810.dirty
#352 lore raw

PATCH v11 8/8 builtin/history: implement "reword" subcommand

In reply to Patrick Steinhardt

Implement a new "reword" subcommand for git-history(1). This subcommand is similar to the user performing an interactive rebase with a single commit changed to use the "reword" instruction.

The "reword" subcommand is built on top of the replay subsystem instead of the sequencer. This leads to some major differences compared to git-rebase(1):

- We do not check out the commit that is to be reworded and instead perform the operation in-memory. This has the obvious benefit of being significantly faster compared to git-rebase(1), but even more importantly it allows the user to rewrite history even if there are local changes in the working tree or in the index.

- We do not execute any hooks, even though we leave some room for changing this in the future.

- By default, all local branches that contain the commit will be rewritten. This especially helps with workflows that use stacked branches.

---
 Documentation/git-history.adoc |  20 +-
 builtin/history.c              | 415 ++++++++++++++++++++++++++++++++++++++++-
 t/meson.build                  |   1 +
 t/t3450-history.sh             |   6 +-
 t/t3451-history-reword.sh      | 391 ++++++++++++++++++++++++++++++++++++++
 5 files changed, 823 insertions(+), 10 deletions(-)
Documentation/git-history.adoc +18 -2
index 68c35f36b9..154e262b76 100644
@@ -8,7 +8,7 @@ git-history - EXPERIMENTAL: Rewrite history
 SYNOPSIS
 --------
 [synopsis]
-git history [<options>]
+git history reword <commit> [--ref-action=(branches|head|print)]
 
 DESCRIPTION
 -----------
@@ -50,7 +50,23 @@ first-class conflicts.
 COMMANDS
 --------
 
-No commands are supported yet.
+The following commands are available to rewrite history in different ways:
+
+`reword <commit>`::
+	Rewrite the commit message of the specified commit. All the other
+	details of this commit remain unchanged. This command will spawn an
+	editor with the current message of that commit.
+
+OPTIONS
+-------
+
+`--ref-action=(branches|head|print)`::
+	Control which references will be updated by the command, if any. With
+	`branches`, all local branches that point to commits which are
+	descendants of the original commit will be rewritten. With `head`, only
+	the current `HEAD` reference will be rewritten. With `print`, all
+	updates as they would be performed with `branches` are printed in a
+	format that can be consumed by linkgit:git-update-ref[1].
 
 GIT
 ---
builtin/history.c +410 -5

432 lines not on this page · raw message

t/meson.build +1 -0
index 73006b095a..c9f92450dc 100644
@@ -388,6 +388,7 @@ integration_tests = [
   't3437-rebase-fixup-options.sh',
   't3438-rebase-broken-files.sh',
   't3450-history.sh',
+  't3451-history-reword.sh',
   't3500-cherry.sh',
   't3501-revert-cherry-pick.sh',
   't3502-cherry-pick-merge.sh',
t/t3450-history.sh +3 -3
index 417c343d43..f513463b92 100755
@@ -5,13 +5,13 @@ test_description='tests for git-history command'
 . ./test-lib.sh
 
 test_expect_success 'does nothing without any arguments' '
-	git history >out 2>&1 &&
-	test_must_be_empty out
+	test_must_fail git history 2>err &&
+	test_grep "need a subcommand" err
 '
 
 test_expect_success 'raises an error with unknown argument' '
 	test_must_fail git history garbage 2>err &&
-	test_grep "unrecognized argument: garbage" err
+	test_grep "unknown subcommand: .garbage." err
 '
 
 test_done
t/t3451-history-reword.sh new file +391 -0

391 lines not on this page · raw message

Signature · 1 line
2.52.0.590.g1f87b77810.dirty
#353 lore raw

Re: [PATCH v11 8/8] builtin/history: implement "reword" subcommand

Quoted 8 lines · Patrick Steinhardt

Implement a new "reword" subcommand for git-history(1). This subcommand is similar to the user performing an interactive rebase with a single commit changed to use the "reword" instruction.

The "reword" subcommand is built on top of the replay subsystem instead of the sequencer. This leads to some major differences compared to git-rebase(1):

Quoted 5 lines

- We do not check out the commit that is to be reworded and instead perform the operation in-memory. This has the obvious benefit of being significantly faster compared to git-rebase(1), but even more importantly it allows the user to rewrite history even if there are local changes in the working tree or in the index.

In an earlier round I pointed out some of the differences between the 'reword' instruction of 'git rebase' and 'git history rebase', including some drawbacks of the latter. It's disheartening to see that you only picked those differences that are in favor of your 'git history' command, but neglected its drawbacks.

Please strive for less biased and more objective commit messages.

Quoted 6 lines

- We do not execute any hooks, even though we leave some room for changing this in the future.

- By default, all local branches that contain the commit will be rewritten. This especially helps with workflows that use stacked branches.

Please don't just state that all local branches containing the modified commit are rewritten, but justify why it behaves that way.

Git's porcelain commands operate on the current branch, unless the user specifies a different branch or an option like '--all' or '--branches'. The default chosen here is inconsistent with the rest of Git.

This is a bad default for any future subcommands implementing common history rewriting operations that can cause conflicts.

Users must remember to specify a non-default '--ref-action' if they don't want this behavior. If they forget to do so and don't notice it, the old commits will be gc-ed away. Therefore, I consider this to be a dangerous default that can lead to data loss.

I firmly believe that operating on all local branches must always be the result of an explicit user action.

#354 lore raw

Re: [PATCH v11 8/8] builtin/history: implement "reword" subcommand

Quoted 16 lines · SZEDER Gábor
Quoted 8 lines · Patrick Steinhardt

Implement a new "reword" subcommand for git-history(1). This subcommand is similar to the user performing an interactive rebase with a single commit changed to use the "reword" instruction.

The "reword" subcommand is built on top of the replay subsystem instead of the sequencer. This leads to some major differences compared to git-rebase(1):

Quoted 5 lines

- We do not check out the commit that is to be reworded and instead perform the operation in-memory. This has the obvious benefit of being significantly faster compared to git-rebase(1), but even more importantly it allows the user to rewrite history even if there are local changes in the working tree or in the index.

Quoted 5 lines

In an earlier round I pointed out some of the differences between the 'reword' instruction of 'git rebase' and 'git history rebase', including some drawbacks of the latter. It's disheartening to see that you only picked those differences that are in favor of your 'git history' command, but neglected its drawbacks.

That'd be https://lore.kernel.org/git/[email protected]/ , right? I see two things you commented on there. Although I'm not Patrick, let me respond to each, in reverse order:

Personally, I'm having difficulty understanding your second stated advantage of picking the commit from the rebase instruction sheet. That instruction sheet is obtained by rebasing on top of something, and it seems as easy to me to see the commits since that point in a git log command and pick your desired commit from log output as it is to invoke an interactive rebase on top of that base commit to get the rebase instruction sheet and then pick out your desired commit from there. Same number of operations and work either way, so I don't see how either is more or less work than the other.

You did make a good point that one of the differences is that you don't have the commit checked out. That's a useful distinction to be aware of. To me, that seems to be somewhat implied already both by "in-memory" and "even if there are local changes in the working tree or index", though it wouldn't hurt to explicitly call it out.

Quoted 1 line

Please strive for less biased and more objective commit messages.

He rewrote the commit message from v6 to v7
(https://lore.kernel.org/git/[email protected]/
-> https://lore.kernel.org/git/[email protected]/),
as far as I can tell precisely to respond to your feedback. Perhaps
he didn't achieve what you wanted, but why jump to the conclusion of
"bias" rather than that he missed conveying an important distinction
as clearly as you wanted?

Quoted 9 lines
Quoted 6 lines

- We do not execute any hooks, even though we leave some room for changing this in the future.

- By default, all local branches that contain the commit will be rewritten. This especially helps with workflows that use stacked branches.

Please don't just state that all local branches containing the modified commit are rewritten, but justify why it behaves that way.

It feels like each of your complaints with the new proposed commands (given commit not checked out, rebase instruction sheet vs listing commit, and HEAD-only) can be boiled down to the fact that they don't behave like git rebase. Is that accurate? If you like rebase, is there a reason you are worried you can't just keep using it? I don't see why others should be required to implement another exact copy of rebase, though. Further, if we only wanted minor modifications, we could have just done those to git rebase.

If you aren't just arguing to match git rebase's behavior exactly, let me try to explain the all-descendant-branches thing from my angle.

One of the issues that I've long hated about git rebase is that if you have multiple inter-dependent branches, it's a royal pain to rebase them all. You cannot rebase them independently, because that disconnects the history by duplicating the shared portions so that you have N copies of each of those. And I couldn't see a way to fix that inside git rebase; its design basically ties you to a single branch.

Further, maybe it'd be useful to explore the different proposed defaults a bit with the 'history reword' example. Let's assume we used your preferred default (rewrite only a single branch) for a user who didn't like that default. If a user does a history reword, and later realizes that their other branches didn't get updated, how do they fix the others? They might be inclined to loop over the other branches and do a 'git history reword CommitZ' on each of them, but then they'd get the nasty surprise of having N different reworded CommitZ's (even if they reworded identically), one per branch. Alternatively, if they are aware that they can't simply reuse the same command to replay the other branches, they'll then start asking questions about how exactly to fix up all the other branches...and the command(s) they need to run is going to be a lot more complicated, especially if they have since added additional commits on top of the active branch that they don't want to undo and lose. It feels like a hard recovery story. In contrast, we can consider the case of the default being to update all branches for a user who doesn't want it. If that user finds that other local branches were also rebased and they didn't want them to be, they just go reset that branch or branches from the reflog, which is pretty easy.

Quoted 4 lines

Git's porcelain commands operate on the current branch, unless the user specifies a different branch or an option like '--all' or '--branches'. The default chosen here is inconsistent with the rest of Git.

That's a good point that there are existing commands that default to the current branch. By my accounting, commands that operate on a range of commits are:
"view a range of commits": log, and derivatives like rev-list "edit a range of commits": fast-import, filter-branch, filter-repo,
rebase, replay
"copy a range of commits (or copy their inverse)": cherry-pick, revert

Hopefully I didn't miss any from skimming over 'git help --all'; my apologies if so. Anyway, let's consider these commands, in reverse order:

I'm not sure the "copy a range of commits" provide much of a precedent for editing a range, since the replay equivalent was always envisioned to only update a single branch for those despite otherwise being envisioned as a rewrite-all-branches-by-default thing. But there's actually a unifying piece of logic that can lead you to the different branch handling: we want to avoid having duplicates of commits simultaneously in use and thus default to as few copies as possible. That logic means that for "copy a range", we apply them to just one branch. The same logic for "edit a range", means to rebase all descendants on any local branch.

For the "edit a range of commits", filter-branch did default to a single branch but is deeply deprecated and more or less warns you that the whole tool was a design mistake. The replacement (filter-repo) in its name makes it clear that one of the mistakes was single branch vs. all branches. fast-import is also more of an all-branch thing, though it doesn't so much have a default. git-rebase does have a single-branch precedent, but that was called out rather strongly in my design goals for its newer alternative, git-replay ("Decapitate HEAD-centric assumptions",
https://lore.kernel.org/git/[email protected]/).
If I hadn't viewed the single-branch handling in rebase as a mistake, I probably would have never created git-replay and instead just incrementally improved git-rebase. Since it was that mistake that lead to new tools in the first place, I'm not sure how much of a precedent git-rebase should be considered to be setting here.

For "viewing a range of commits", git log does lend towards your argument; it could be seen as precedent setting in favor of just-the-current-branch.

So, the precedent seems to not be uniform among git commands, though I think git log is strongly in your favor. As a really rough measure of how much that precedent matters, we can look at how folks have commented on what they think the default should be so far in this whole thread:

Rebase-all-descendant branches:
* Phillip (https://lore.kernel.org/git/[email protected]/)
* Junio (https://lore.kernel.org/git/[email protected]/)
* Kristoffer (https://lore.kernel.org/git/[email protected]/)
* Ben (https://lore.kernel.org/git/[email protected]/)
* me (this email, among others)
* Martin (https://lore.kernel.org/git/CANiSa6hxjghKQMhURx8qC2t=+1gEE7p8YaHbWkg3rYOYa=poVg@mail.gmail.com/)
* Patrick ("Yup" from
https://lore.kernel.org/git/[email protected]/, plus this v11
we're responding to, though he did seem to vacillate over the course
of the series)

Rebase-current-branch-only:
* You (your email that I'm responding to)

Do not allow editing a commit shared by multiple branches:
* Matthias (https://lore.kernel.org/git/4m6rmefbv4hftclimitz5rp6yapswjtnjsxymrsdkuan4jbg3u@dm5jzdiq5cxz/)

(Sorry if I missed any, I tried to find them all in the threads on this topic.)

Quoted 2 lines

This is a bad default for any future subcommands implementing common history rewriting operations that can cause conflicts.

Totally disagree; we'd want rebase-all-descendant-local-branches for those commands too. In fact, that's precisely what I did with "git replay edit". (True, "git replay edit" was just a proof-of-concept because I didn't have conflict handling implemented, but it was very much an intentional default for a command known to need to deal with conflicts before being productionized).

Further, we have two semi-independent implementations of replay-all-descendant-branches-by-default in the form of JJ and GitButler, with real world use (not just demos) and apparent consensus that it not only works but was a good decision.

So, I'm a little unsure at how you arrived at this conclusion; do you care to elucidate?

Quoted 4 lines

Users must remember to specify a non-default '--ref-action' if they don't want this behavior. If they forget to do so and don't notice it, the old commits will be gc-ed away. Therefore, I consider this to be a dangerous default that can lead to data loss.

You elided over "for a really long time so that the reflogs expire", but you bring up a good point. I think the key here is "don't notice it". With "git replay edit", I'd print notices about what was updated after each operation (particularly important since the operation could be a git commit --amend or git reset HEAD~1 or whatever, which causes commits which are the descendants of the one you are operating on to be replayed). To avoid the "don't notice it" issue, we could do the same with Patrick's history command. We could also prevent a forgotten --ref-action by allowing a config variable, which I'll cover more below.

Quoted 2 lines

I firmly believe that operating on all local branches must always be the result of an explicit user action.

Over at https://lore.kernel.org/git/[email protected]/ , you alternatively suggested the idea of an "escape hatch". I think that may be a good idea. What if we had a "history.scope" config variable, with values like "descendant-branches", "current-branch", and "error-if-multiple-branches", corresponding to each of the requested defaults we've seen in response to this series? I can't imagine using anything other than descendant-branches, and the preponderance of those who have commented on the default so far seem to be in agreement, but it would allow you and Matthias and others like you two to pick an alternative. Thoughts?

#355 lore raw

Re: [PATCH v11 8/8] builtin/history: implement "reword" subcommand

Quoted 6 lines · Elijah Newren

... that they don't want to undo and lose. It feels like a hard recovery story. In contrast, we can consider the case of the default being to update all branches for a user who doesn't want it. If that user finds that other local branches were also rebased and they didn't want them to be, they just go reset that branch or branches from the reflog, which is pretty easy.

Very nicely put. I originally thought that the "reflog is your friend" argument would apply in both direction, but leaving the tips of some branches behind while rewriting the tips of some other branches, that can reach the tips of these left-bhind branches, would mean we have no other commit to go back to.

Thanks.

#356 lore raw

Re: [PATCH v11 8/8] builtin/history: implement "reword" subcommand

In reply to Elijah Newren
Quoted 31 lines · Elijah Newren
Quoted 1 line · SZEDER Gábor

...
Personally, I'm having difficulty understanding your second stated advantage of picking the commit from the rebase instruction sheet. That instruction sheet is obtained by rebasing on top of something, and it seems as easy to me to see the commits since that point in a git log command and pick your desired commit from log output as it is to invoke an interactive rebase on top of that base commit to get the rebase instruction sheet and then pick out your desired commit from there. Same number of operations and work either way, so I don't see how either is more or less work than the other.

You did make a good point that one of the differences is that you don't have the commit checked out. That's a useful distinction to be aware of. To me, that seems to be somewhat implied already both by "in-memory" and "even if there are local changes in the working tree or index", though it wouldn't hurt to explicitly call it out.

It feels like each of your complaints with the new proposed commands (given commit not checked out, rebase instruction sheet vs listing commit, and HEAD-only) can be boiled down to the fact that they don't behave like git rebase. Is that accurate? If you like rebase, is there a reason you are worried you can't just keep using it? I don't see why others should be required to implement another exact copy of rebase, though. Further, if we only wanted minor modifications, we could have just done those to git rebase.

Quoted 2 lines

I firmly believe that operating on all local branches must always be the result of an explicit user action.

Quoted 10 lines

Over at https://lore.kernel.org/git/[email protected]/ , you alternatively suggested the idea of an "escape hatch". I think that may be a good idea. What if we had a "history.scope" config variable, with values like "descendant-branches", "current-branch", and "error-if-multiple-branches", corresponding to each of the requested defaults we've seen in response to this series? I can't imagine using anything other than descendant-branches, and the preponderance of those who have commented on the default so far seem to be in agreement, but it would allow you and Matthias and others like you two to pick an alternative. Thoughts?

The discussion stalled after this exchange. What is the next move? I think the it is SZEDER's turn to respond?

The topic is depended on Phillip's "git replay" tweak to drop commits that are originally not-empty and become empty in the replayed history, blocking its advance, which is doubly unfortunate.

Thanks.

#357 lore raw

Re: [PATCH v11 8/8] builtin/history: implement "reword" subcommand

Quoted 21 lines · Junio C Hamano
Quoted 19 lines · Elijah Newren
Quoted 1 line · SZEDER Gábor

...
Personally, I'm having difficulty understanding your second stated advantage of picking the commit from the rebase instruction sheet. That instruction sheet is obtained by rebasing on top of something, and it seems as easy to me to see the commits since that point in a git log command and pick your desired commit from log output as it is to invoke an interactive rebase on top of that base commit to get the rebase instruction sheet and then pick out your desired commit from there. Same number of operations and work either way, so I don't see how either is more or less work than the other.

You did make a good point that one of the differences is that you don't have the commit checked out. That's a useful distinction to be aware of. To me, that seems to be somewhat implied already both by "in-memory" and "even if there are local changes in the working tree or index", though it wouldn't hurt to explicitly call it out.

Quoted 8 lines
Quoted 8 lines

It feels like each of your complaints with the new proposed commands (given commit not checked out, rebase instruction sheet vs listing commit, and HEAD-only) can be boiled down to the fact that they don't behave like git rebase. Is that accurate? If you like rebase, is there a reason you are worried you can't just keep using it? I don't see why others should be required to implement another exact copy of rebase, though. Further, if we only wanted minor modifications, we could have just done those to git rebase.

git-history(1) is definitely quite different compared to git-rebase(1), and that's by design. Not everyone will like it, and many folks will probably continue to just use git-rebase(1) themselves. But as you say, it does address some use cases that git-rebase(1) doesn't handle itself, and it tries to provide an opinionated interface to make common tasks easier to handle for folks who aren't advanced users.

I of course wouldn't mind highlighting more of the differences in the docs and/or the commit message, of course. It's tough sometimes to find the right level of details.

Quoted 13 lines
Quoted 13 lines
Quoted 2 lines

I firmly believe that operating on all local branches must always be the result of an explicit user action.

Over at https://lore.kernel.org/git/[email protected]/ , you alternatively suggested the idea of an "escape hatch". I think that may be a good idea. What if we had a "history.scope" config variable, with values like "descendant-branches", "current-branch", and "error-if-multiple-branches", corresponding to each of the requested defaults we've seen in response to this series? I can't imagine using anything other than descendant-branches, and the preponderance of those who have commented on the default so far seem to be in agreement, but it would allow you and Matthias and others like you two to pick an alternative. Thoughts?

I would certainly be happy to add such an escape hatch to the command so that it only rewrites the current branch. We already have the infrastructure for that in place anyway, so it's trivial to add a configuration key that changes the default.

Quoted 2 lines

The discussion stalled after this exchange. What is the next move? I think the it is SZEDER's turn to respond?

I dunno. From my point of view I still believe this is ready to be merged. Sure, there will be follow-up topics:

- The above configuration to make it work on a single branch, only.

- First-class conflicts. This is something that I also discussed with Elijah already, and we will coordinate on this topic going forward.

- Additional subcommands, of course.

But I don't think that missing support for first-class conflicts needs to hold back this topic. The proposed command cannot result in conflicts anyway, and there's more commands that won't. Furthermore, the command is marked as experimental, so the initial versions are expected to be somewhat limited in their functionality so that we can get feedback and iterate on the design if we see that it needs some tweaking.

Thanks!

Patrick

#358 lore raw
In reply to Patrick Steinhardt

On Tue, Jan 13, 2026 at 1:54 AM Patrick Steinhardt <[email protected]> wrote:
[...]

Quoted 9 lines

Changes in v11:
- Fix overly clever BUG() condition.
- Drop the struct replay_result::merge_conflict field.
- Return a positive value from replay_revisions() in case there was
a conflict.
- Improve a commit message.
- Fix check for whether setup_revisions_from_strvec() was
successful.
- Link to v10: https://lore.kernel.org/r/[email protected]

This version looks good to merge down.

#359 lore raw
Quoted 12 lines · Elijah Newren

On Tue, Jan 13, 2026 at 1:54 AM Patrick Steinhardt <[email protected]> wrote:
[...]

Quoted 9 lines

Changes in v11:
- Fix overly clever BUG() condition.
- Drop the struct replay_result::merge_conflict field.
- Return a positive value from replay_revisions() in case there was
a conflict.
- Improve a commit message.
- Fix check for whether setup_revisions_from_strvec() was
successful.
- Link to v10: https://lore.kernel.org/r/[email protected]

Quoted 1 line

This version looks good to merge down.

Thanks.

#360 lore raw
Quoted 14 lines · Junio C Hamano
Quoted 12 lines · Elijah Newren

On Tue, Jan 13, 2026 at 1:54 AM Patrick Steinhardt <[email protected]> wrote:
[...]

Quoted 9 lines

Changes in v11:
- Fix overly clever BUG() condition.
- Drop the struct replay_result::merge_conflict field.
- Return a positive value from replay_revisions() in case there was
a conflict.
- Improve a commit message.
- Fix check for whether setup_revisions_from_strvec() was
successful.
- Link to v10: https://lore.kernel.org/r/[email protected]

Quoted 3 lines
Quoted 1 line

This version looks good to merge down.

Thanks.

FWIW, I think it's far from ready to be merged.

#361 lore raw
Quoted 15 lines · SZEDER Gábor
Quoted 14 lines · Junio C Hamano
Quoted 12 lines · Elijah Newren

On Tue, Jan 13, 2026 at 1:54 AM Patrick Steinhardt <[email protected]> wrote:
[...]

Quoted 9 lines

Changes in v11:
- Fix overly clever BUG() condition.
- Drop the struct replay_result::merge_conflict field.
- Return a positive value from replay_revisions() in case there was
a conflict.
- Improve a commit message.
- Fix check for whether setup_revisions_from_strvec() was
successful.
- Link to v10: https://lore.kernel.org/r/[email protected]

Quoted 5 lines
Quoted 3 lines
Quoted 1 line

This version looks good to merge down.

Thanks.

FWIW, I think it's far from ready to be merged.

Will the discussion continue in the other subthread, i.e.,

https://lore.kernel.org/git/CABPp-BHkNLdH4C7U4sFoVhrsSPH8KAaDtOdLEQGyajmXZz9hVg@mail.gmail.com/