rebase -i: offer to recreate merge commits
PATCH v4 1/4 rebase -i: demonstrate bugs with fixup!/squash! commit messages
In reply to Johannes SchindelinWhen multiple fixup/squash commands are processed and the last one causes merge conflicts and is skipped, we leave the "This is a combination of ..." comments in the commit message.
Noticed by Eric Sunshine.
This regression test also demonstrates that we rely on the localized version of
# This is a combination of <number> commits
to contain the <number> in ASCII, which breaks under GETTEXT_POISON.
--- t/t3418-rebase-continue.sh | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+)
t/t3418-rebase-continue.sh +22 -0
@@ -88,6 +88,28 @@ test_expect_success 'rebase passes merge strategy options correctly' ' git rebase --continue ' +test_expect_failure '--skip after failed fixup cleans commit message' ' + test_when_finished "test_might_fail git rebase --abort" && + git checkout -b with-conflicting-fixup && + test_commit wants-fixup && + test_commit "fixup! wants-fixup" wants-fixup.t 1 wants-fixup-1 && + test_commit "fixup! wants-fixup" wants-fixup.t 2 wants-fixup-2 && + test_commit "fixup! wants-fixup" wants-fixup.t 3 wants-fixup-3 && + test_must_fail env FAKE_LINES="1 fixup 2 fixup 4" \ + git rebase -i HEAD~4 && + + : now there is a conflict, and comments in the commit message && + git show HEAD >out && + grep "fixup! wants-fixup" out && + + : skip and continue && + git rebase --skip && + + : now the comments in the commit message should have been cleaned up && + git show HEAD >out && + ! grep "fixup! wants-fixup" out +' + test_expect_success 'setup rerere database' ' rm -fr .git/rebase-* && git reset --hard commit-new-file-F3-on-topic-branch &&
Signature · 1 line
2.17.0.windows.1.33.gfcbb1fa0445
PATCH v4 2/4 rebase -i: Handle "combination of <n> commits" with GETTEXT_POISON
In reply to Johannes SchindelinWe previously relied on the localized versions of
# This is a combination of <N> commits
(which we write into the commit messages during fixup/squash chains) to contain <N> encoded in ASCII.
This is not true in general, and certainly not true when compiled with GETTEXT_POISON=TryToKillMe, as demonstrated by the regression test we just introduced in t3418.
So let's decouple keeping track of the count from the (localized) commit messages by introducing a new file called 'current-fixups' that keeps track of the current fixup/squash chain. This file contains a bit more than just the count (it contains a list of "fixup <commit>"/"squash <commit>" lines). This is done on purpose, as it will come in handy for a fix for the bug where git rebase --skip on a final fixup/squash will leave the commit message in limbo.
--- sequencer.c | 78 ++++++++++++++++++++++++++++++----------------------- sequencer.h | 6 ++++- 2 files changed, 49 insertions(+), 35 deletions(-)
sequencer.c +44 -34
@@ -74,13 +74,6 @@ static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")* previous commit and from the first squash/fixup commit are written * to it. The commit message for each subsequent squash/fixup commit * is appended to the file as it is processed. -* -* The first line of the file is of the form -* # This is a combination of $count commits. -* where $count is the number of commits whose messages have been -* written to the file so far (including the initial "pick" commit). -* Each time that a commit message is processed, this line is read and -* updated. It is deleted just before the combined commit is made. */ static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")/*
@@ -91,6 +84,11 @@ static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")* commit without opening the editor.) */ static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup") +/* +* This file contains the list fixup/squash commands that have been +* accumulated into message-fixup or message-squash so far. + */ +staticGIT_PATH_FUNC (rebase_path_current_fixups,"rebase-merge/current-fixups" )/* * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and * GIT_AUTHOR_DATE that will be used for the commit that is currently
@@ -253,6 +251,7 @@ int sequencer_remove_state(struct replay_opts *opts)for (i =0 ; i < opts->xopts_nr; i++)free (opts->xopts[i]);free (opts->xopts); +strbuf_release (&opts->current_fixups);strbuf_addstr (&dir,get_dir (opts));remove_dir_recursively (&dir,0 );
@@ -1329,34 +1328,23 @@ static int update_squash_messages(enum todo_command command, struct commit *commit, struct replay_opts *opts) { struct strbuf buf = STRBUF_INIT; -int count, res; +int res;const char *message, *body; -if (file_exists (rebase_path_squash_msg ())) { +if (opts->current_fixup_count >0 ) {struct strbuf header =STRBUF_INIT ; -char *eol, *p; +char *eol; -if (strbuf_read_file (&buf,rebase_path_squash_msg (),2048 ) <=0 ) +if (strbuf_read_file (&buf,rebase_path_squash_msg (),9 ) <=0 )return error (_ ("could not read '%s'" ),rebase_path_squash_msg ()); - p = buf.buf +1 ; - eol =strchrnul (buf.buf,'\n' ); -if (buf.buf[0 ] != comment_line_char || - (p +=strcspn (p,"0123456789\n" )) == eol) -return error (_ ("unexpected 1st line of squash message:" -"\n\n\t%.*s" ), - (int )(eol - buf.buf), buf.buf); - count =strtol (p,NULL ,10 ); - -if (count <1 ) -return error (_ ("invalid 1st line of squash message:\n" -"\n\t%.*s" ), - (int )(eol - buf.buf), buf.buf); + eol = buf.buf[0 ] != comment_line_char ? + buf.buf :strchrnul (buf.buf,'\n' );strbuf_addf (&header,"%c " , comment_line_char); -strbuf_addf (&header, -_ ("This is a combination of %d commits." ), ++count); +strbuf_addf (&header,_ ("This is a combination of %d commits." ), + opts->current_fixup_count +2 );strbuf_splice (&buf,0 , eol - buf.buf, header.buf, header.len);strbuf_release (&header); }else {
@@ -1379,10 +1367,8 @@ static int update_squash_messages(enum todo_command command, rebase_path_fixup_msg()); } - count =2 ;strbuf_addf (&buf,"%c " , comment_line_char); -strbuf_addf (&buf,_ ("This is a combination of %d commits." ), - count); +strbuf_addf (&buf,_ ("This is a combination of %d commits." ),2 );strbuf_addf (&buf,"\n%c " , comment_line_char);strbuf_addstr (&buf,_ ("This is the 1st commit message:" ));strbuf_addstr (&buf,"\n\n" );
@@ -1399,13 +1385,14 @@ static int update_squash_messages(enum todo_command command,if (command ==TODO_SQUASH ) {unlink (rebase_path_fixup_msg ());strbuf_addf (&buf,"\n%c " , comment_line_char); -strbuf_addf (&buf,_ ("This is the commit message #%d:" ), count); +strbuf_addf (&buf,_ ("This is the commit message #%d:" ), + ++opts->current_fixup_count);strbuf_addstr (&buf,"\n\n" );strbuf_addstr (&buf, body); }else if (command ==TODO_FIXUP ) {strbuf_addf (&buf,"\n%c " , comment_line_char);strbuf_addf (&buf,_ ("The commit message #%d will be skipped:" ), - count); + ++opts->current_fixup_count);strbuf_addstr (&buf,"\n\n" );strbuf_add_commented_lines (&buf, body,strlen (body)); }else
@@ -1414,6 +1401,17 @@ static int update_squash_messages(enum todo_command command, res =write_message (buf.buf, buf.len,rebase_path_squash_msg (),0 );strbuf_release (&buf); + +if (!res) { +strbuf_addf (&opts->current_fixups,"%s%s %s" , + opts->current_fixups.len ?"\n" :"" , +command_to_string (command), +oid_to_hex (&commit->object.oid)); + res =write_message (opts->current_fixups.buf, + opts->current_fixups.len, +rebase_path_current_fixups (),0 ); + } +return res; }
@@ -1676,6 +1674,9 @@ static int do_pick_commit(enum todo_command command, struct commit *commit,if (!res && final_fixup) {unlink (rebase_path_fixup_msg ());unlink (rebase_path_squash_msg ()); +unlink (rebase_path_current_fixups ()); +strbuf_reset (&opts->current_fixups); + opts->current_fixup_count =0 ; } leave:
@@ -2052,6 +2053,16 @@ static int read_populate_opts(struct replay_opts *opts)read_strategy_opts (opts, &buf);strbuf_release (&buf); +if (read_oneliner (&opts->current_fixups, +rebase_path_current_fixups (),1 )) { +const char *p = opts->current_fixups.buf; + opts->current_fixup_count =1 ; +while ((p =strchr (p,'\n' ))) { + opts->current_fixup_count++; + p++; + } + } +return 0 ; }
@@ -2398,10 +2409,9 @@ static int error_with_patch(struct commit *commit,static int error_failed_squash (struct commit *commit,struct replay_opts *opts,int subject_len,const char *subject) { -if (rename (rebase_path_squash_msg (),rebase_path_message ())) -return error (_ ("could not rename '%s' to '%s'" ), +if (copy_file (rebase_path_message (),rebase_path_squash_msg (),0666 )) +return error (_ ("could not copy '%s' to '%s'" ),rebase_path_squash_msg (),rebase_path_message ()); -unlink (rebase_path_fixup_msg ());unlink (git_path_merge_msg ());if (copy_file (git_path_merge_msg (),rebase_path_message (),0666 )) return error(_("could not copy '%s' to '%s'"),
sequencer.h +5 -1
@@ -44,10 +44,14 @@ struct replay_opts {char **xopts;size_t xopts_nr, xopts_alloc; +/* Used by fixup/squash */ +struct strbuf current_fixups; +int current_fixup_count; +/* Only used by REPLAY_NONE */ struct rev_info *revs; }; -#define REPLAY_OPTS_INIT { -1 } +#define REPLAY_OPTS_INIT { .action = -1, .current_fixups = STRBUF_INIT }/* Call this to setup defaults before parsing command line options */ void sequencer_init_config (struct replay_opts *opts);
Signature · 1 line
2.17.0.windows.1.33.gfcbb1fa0445
PATCH v4 3/4 sequencer: always commit without editing when asked for
In reply to Johannes SchindelinPreviously, we only called run_git_commit() without EDIT_MSG when we also passed in a default message.
However, an upcoming caller will want to commit without EDIT_MSG and *without* a default message: to clean up fixup/squash comments in HEAD's commit message.
Let's prepare for that.
--- sequencer.c | 2 ++ 1 file changed, 2 insertions(+)
sequencer.c +2 -0
@@ -717,6 +717,8 @@ static int run_git_commit(const char *defmsg, struct replay_opts *opts,argv_array_pushf (&cmd.args,"-S%s" , opts->gpg_sign);if (defmsg)argv_array_pushl (&cmd.args,"-F" , defmsg,NULL ); +else if (!(flags &EDIT_MSG )) +argv_array_pushl (&cmd.args,"-C" ,"HEAD" ,NULL );if ((flags &CLEANUP_MSG ))argv_array_push (&cmd.args,"--cleanup=strip" );if ((flags &EDIT_MSG ))
Signature · 1 line
2.17.0.windows.1.33.gfcbb1fa0445
PATCH v4 4/4 rebase --skip: clean up commit message after a failed fixup/squash
In reply to Johannes SchindelinDuring a series of fixup/squash commands, the interactive rebase builds up a commit message with comments. This will be presented to the user in the editor if at least one of those commands was a squash.
In any case, the commit message will be cleaned up eventually, removing all those intermediate comments, in the final step of such a fixup/squash chain.
However, if the last fixup/squash command in such a chain fails with merge conflicts, and if the user then decides to skip it (or resolve it to a clean worktree and then continue the rebase), the current code fails to clean up the commit message.
This commit fixes that behavior.
The fix is quite a bit more involved than meets the eye because it is not only about the question whether we are git rebase --skiping a fixup or squash. It is also about removing the skipped fixup/squash's commit message from the accumulated commit message. And it is also about the question whether we should let the user edit the final commit message or not ("Was there a squash in the chain *that was not skipped*?").
For example, in this case we will want to fix the commit message, but not open it in an editor:
pick <- succeeds
fixup <- succeeds
squash <- fails, will be skipped
This is where the newly-introduced current-fixups file comes in real handy. A quick look and we can determine whether there was a non-skipped squash. We only need to make sure to keep it up to date with respect to skipped fixup/squash commands. As a bonus, we can even avoid committing unnecessarily, e.g. when there was only one fixup, and it failed, and was skipped.
To fix only the bug where the final commit message was not cleaned up properly, but without fixing the rest, would have been more complicated than fixing it all in one go, hence this commit lumps together more than a single concern.
For the same reason, this commit also adds a bit more to the existing test case for the regression we just fixed.
The diff is best viewed with --color-moved.
--- sequencer.c | 113 ++++++++++++++++++++++++++++++++----- t/t3418-rebase-continue.sh | 35 ++++++++++-- 2 files changed, 131 insertions(+), 17 deletions(-)
sequencer.c +100 -13
@@ -2779,19 +2779,16 @@ static int continue_single_pick(void)return run_command_v_opt (argv,RUN_GIT_CMD ); } -static int commit_staged_changes (struct replay_opts *opts) +static int commit_staged_changes (struct replay_opts *opts, +struct todo_list *todo_list) {unsigned int flags =ALLOW_EMPTY |EDIT_MSG ; +unsigned int final_fixup =0 , is_clean;if (has_unstaged_changes (1 ))return error (_ ("cannot rebase: You have unstaged changes." )); -if (!has_uncommitted_changes (0 )) { -const char *cherry_pick_head =git_path_cherry_pick_head (); -if (file_exists (cherry_pick_head) &&unlink (cherry_pick_head)) -return error (_ ("could not remove CHERRY_PICK_HEAD" )); -return 0 ; - } + is_clean = !has_uncommitted_changes (0 );if (file_exists (rebase_path_amend ())) {struct strbuf rev =STRBUF_INIT ;
@@ -2804,19 +2801,107 @@ static int commit_staged_changes(struct replay_opts *opts)if (get_oid_hex (rev.buf, &to_amend))return error (_ ("invalid contents: '%s'" ),rebase_path_amend ()); -if (oidcmp (&head, &to_amend)) +if (!is_clean &&oidcmp (&head, &to_amend))return error (_ ("\nYou have uncommitted changes in your " "working tree. Please, commit them\n" "first and then run 'git rebase " "--continue' again." )); +/* +* When skipping a failed fixup/squash, we need to edit the +* commit message, the current fixup list and count, and if it +* was the last fixup/squash in the chain, we need to clean up +* the commit message and if there was a squash, let the user +* edit it. +*/ +if (is_clean && !oidcmp (&head, &to_amend) && + opts->current_fixup_count >0 && +file_exists (rebase_path_stopped_sha ())) { +const char *p = opts->current_fixups.buf; +int len = opts->current_fixups.len; + + opts->current_fixup_count--; +if (!len) +BUG ("Incorrect current_fixups:\n%s" , p); +while (len && p[len -1 ] !='\n' ) + len--; +strbuf_setlen (&opts->current_fixups, len); +if (write_message (p, len,rebase_path_current_fixups (), +0 ) <0 ) +return error (_ ("could not write file: '%s'" ), +rebase_path_current_fixups ()); + +/* +* If a fixup/squash in a fixup/squash chain failed, the +* commit message is already correct, no need to commit +* it again. +* +* Only if it is the final command in the fixup/squash +* chain, and only if the chain is longer than a single +* fixup/squash command (which was just skipped), do we +* actually need to re-commit with a cleaned up commit +* message. +*/ +if (opts->current_fixup_count >0 && + !is_fixup (peek_command (todo_list,0 ))) { + final_fixup =1 ; +/* +* If there was not a single "squash" in the +* chain, we only need to clean up the commit +* message, no need to bother the user with +* opening the commit message in the editor. +*/ +if (!starts_with (p,"squash " ) && + !strstr (p,"\nsquash " )) + flags = (flags & ~EDIT_MSG ) |CLEANUP_MSG ; + }else if (is_fixup (peek_command (todo_list,0 ))) { +/* +* We need to update the squash message to skip +* the latest commit message. +*/ +struct commit *commit; +const char *path =rebase_path_squash_msg (); + +if (parse_head (&commit) || + !(p =get_commit_buffer (commit,NULL )) || +write_message (p,strlen (p), path,0 )) { +unuse_commit_buffer (commit, p); +return error (_ ("could not write file: " +"'%s'" ), path); + } +unuse_commit_buffer (commit, p); + } + }strbuf_release (&rev); flags |=AMEND_MSG ; } -if (run_git_commit (rebase_path_message (), opts, flags)) +if (is_clean) { +const char *cherry_pick_head =git_path_cherry_pick_head (); + +if (file_exists (cherry_pick_head) &&unlink (cherry_pick_head)) +return error (_ ("could not remove CHERRY_PICK_HEAD" )); +if (!final_fixup) +return 0 ; + } + +if (run_git_commit (final_fixup ?NULL :rebase_path_message (), + opts, flags))return error (_ ("could not commit staged changes." ));unlink (rebase_path_amend ()); +if (final_fixup) { +unlink (rebase_path_fixup_msg ()); +unlink (rebase_path_squash_msg ()); + } +if (opts->current_fixup_count >0 ) { +/* +* Whether final fixup or not, we just cleaned up the commit +* message... +*/ +unlink (rebase_path_current_fixups ()); +strbuf_reset (&opts->current_fixups); + opts->current_fixup_count =0 ; + }return 0 ; }
@@ -2828,14 +2913,16 @@ int sequencer_continue(struct replay_opts *opts)if (read_and_refresh_cache (opts))return -1 ; +if (read_populate_opts (opts)) +return -1 ;if (is_rebase_i (opts)) { -if (commit_staged_changes (opts)) +if ((res =read_populate_todo (&todo_list, opts))) + goto release_todo_list; +if (commit_staged_changes (opts, &todo_list))return -1 ; }else if (!file_exists (get_todo_path (opts)))return continue_single_pick (); -if (read_populate_opts (opts)) -return -1 ; -if ((res =read_populate_todo (&todo_list, opts))) +else if ((res =read_populate_todo (&todo_list, opts))) goto release_todo_list;if (!is_rebase_i (opts)) {
t/t3418-rebase-continue.sh +31 -4
@@ -88,14 +88,14 @@ test_expect_success 'rebase passes merge strategy options correctly' ' git rebase --continue ' -test_expect_failure '--skip after failed fixup cleans commit message' ' +test_expect_success '--skip after failed fixup cleans commit message' ' test_when_finished "test_might_fail git rebase --abort" && git checkout -b with-conflicting-fixup && test_commit wants-fixup && test_commit "fixup! wants-fixup" wants-fixup.t 1 wants-fixup-1 && test_commit "fixup! wants-fixup" wants-fixup.t 2 wants-fixup-2 && test_commit "fixup! wants-fixup" wants-fixup.t 3 wants-fixup-3 && - test_must_fail env FAKE_LINES="1 fixup 2 fixup 4" \ + test_must_fail env FAKE_LINES="1 fixup 2 squash 4" \ git rebase -i HEAD~4 && : now there is a conflict, and comments in the commit message &&
@@ -103,11 +103,38 @@ test_expect_failure '--skip after failed fixup cleans commit message' ' grep "fixup! wants-fixup" out && : skip and continue && - git rebase --skip && + echo "cp \"\$1\" .git/copy.txt" | write_script copy-editor.sh && + (test_set_editor "$PWD/copy-editor.sh" && git rebase --skip) && + + : the user should not have had to edit the commit message && + test_path_is_missing .git/copy.txt && : now the comments in the commit message should have been cleaned up && git show HEAD >out && - ! grep "fixup! wants-fixup" out + ! grep "fixup! wants-fixup" out && + + : now, let us ensure that "squash" is handled correctly && + git reset --hard wants-fixup-3 && + test_must_fail env FAKE_LINES="1 squash 4 squash 2 squash 4" \ + git rebase -i HEAD~4 && + + : the first squash failed, but there are two more in the chain && + (test_set_editor "$PWD/copy-editor.sh" && + test_must_fail git rebase --skip) && + + : not the final squash, no need to edit the commit message && + test_path_is_missing .git/copy.txt && + + : The first squash was skipped, therefore: && + git show HEAD >out && + test_i18ngrep "# This is a combination of 2 commits" out && + + (test_set_editor "$PWD/copy-editor.sh" && git rebase --skip) && + git show HEAD >out && + test_i18ngrep ! "# This is a combination" out && + + : Final squash failed, but there was still a squash && + test_i18ngrep "# This is a combination of 2 commits" .git/copy.txt ' test_expect_success 'setup rerere database' '
Signature · 1 line
2.17.0.windows.1.33.gfcbb1fa0445
Re: [PATCH v4 4/4] rebase --skip: clean up commit message after a failed fixup/squash
Quoted 3 lines · Johannes Schindelin
During a series of fixup/squash commands, the interactive rebase builds up a commit message with comments. This will be presented to the user in the editor if at least one of those commands was a
squash.
This sounds as if the whole series will be presented to the user, i.e.
pick A
squash B
fixup C
would present A+B+C in the editor. I always assumed the sequencer to be linear, i.e. pick A+B, open editor and then fixup C into the previous result?
No need to resend it reworded, I just realize that I never tested my potentially wrong assumption.
Quoted 1 line
The diff is best viewed with --color-moved.
... and web pages are "best viewed with IE 6.0" ;-)
I found this so funny that I had to download the patches and actually look at them
using the move detection only to find out that only very few lines are moved, as there are only very few deleted lines.
Re: [PATCH v4 4/4] rebase --skip: clean up commit message after a failed fixup/squash
Hi Stefan,
Quoted 6 lines · Stefan Beller
Quoted 3 lines · Johannes Schindelin
During a series of fixup/squash commands, the interactive rebase builds up a commit message with comments. This will be presented to the user in the editor if at least one of those commands was a
squash.
Quoted 7 lines
This sounds as if the whole series will be presented to the user, i.e.
pick A
squash B
fixup Cwould present A+B+C in the editor.
And that is indeed the case. The commit message would look something like this:
# This is a combination of 3 commits.
# This is commit message #1:
Hello Stefan
This is A.
# This is commit message #2:
squash! A
Me again, Stefan. I am here to be squashed.
# The commit message #3 will be skipped:
#
# fixup! A
Quoted 2 lines
I always assumed the sequencer to be linear, i.e. pick A+B, open editor and then fixup C into the previous result?
Nope.
Quoted 2 lines
No need to resend it reworded, I just realize that I never tested my potentially wrong assumption.
No worries, you learned something today.
Quoted 3 lines
Quoted 1 line
The diff is best viewed with --color-moved.
... and web pages are "best viewed with IE 6.0" ;-)
That is what I had in mind writing that.
Quoted 3 lines
I found this so funny that I had to download the patches and actually look at them using the move detection only to find out that only very few lines are moved, as there are only very few deleted lines.
I agree that the current iteration is no longer such obvious a move. I had to add tons of stuff to fix the extra issues I found while working on v4.
But still, I found it super-helpful to see that the code was actually moved, and where, because I essentially had to break up the nice sequence of "is it clean? Yes? Then nothing to be done! No? Is HEAD to be amended? Yes? No?" and basically build a matrix what to do in all combinations of "clean? Amend HEAD?"
Ciao,
Dscho
Re: [PATCH v4 4/4] rebase --skip: clean up commit message after a failed fixup/squash
In reply to Johannes SchindelinHi Johannes, sorry it's taken me a while to look at this. I think it mostly makes sense to me, the code is well documented. I've got one comment below
Quoted 144 lines · Johannes Schindelin
During a series of fixup/squash commands, the interactive rebase builds up a commit message with comments. This will be presented to the user in the editor if at least one of those commands was a
squash.In any case, the commit message will be cleaned up eventually, removing all those intermediate comments, in the final step of such a fixup/squash chain.
However, if the last fixup/squash command in such a chain fails with merge conflicts, and if the user then decides to skip it (or resolve it to a clean worktree and then continue the rebase), the current code fails to clean up the commit message.
This commit fixes that behavior.
The fix is quite a bit more involved than meets the eye because it is not only about the question whether we are
git rebase --skiping a fixup or squash. It is also about removing the skipped fixup/squash's commit message from the accumulated commit message. And it is also about the question whether we should let the user edit the final commit message or not ("Was there a squash in the chain *that was not skipped*?").For example, in this case we will want to fix the commit message, but not open it in an editor:
pick <- succeeds
fixup <- succeeds
squash <- fails, will be skippedThis is where the newly-introduced
current-fixupsfile comes in real handy. A quick look and we can determine whether there was a non-skipped squash. We only need to make sure to keep it up to date with respect to skipped fixup/squash commands. As a bonus, we can even avoid committing unnecessarily, e.g. when there was only one fixup, and it failed, and was skipped.To fix only the bug where the final commit message was not cleaned up properly, but without fixing the rest, would have been more complicated than fixing it all in one go, hence this commit lumps together more than a single concern.
For the same reason, this commit also adds a bit more to the existing test case for the regression we just fixed.
The diff is best viewed with --color-moved.
Signed-off-by Johannes Schindelin <[email protected]>--- sequencer.c | 113 ++++++++++++++++++++++++++++++++----- t/t3418-rebase-continue.sh | 35 ++++++++++-- 2 files changed, 131 insertions(+), 17 deletions(-)sequencer.c +57
-8@@ -2779,19 +2779,16 @@ static int continue_single_pick(void)return run_command_v_opt (argv,RUN_GIT_CMD ); } -static int commit_staged_changes (struct replay_opts *opts) +static int commit_staged_changes (struct replay_opts *opts, +struct todo_list *todo_list) {unsigned int flags =ALLOW_EMPTY |EDIT_MSG ; +unsigned int final_fixup =0 , is_clean;if (has_unstaged_changes (1 ))return error (_ ("cannot rebase: You have unstaged changes." )); -if (!has_uncommitted_changes (0 )) { -const char *cherry_pick_head =git_path_cherry_pick_head (); -if (file_exists (cherry_pick_head) &&unlink (cherry_pick_head)) -return error (_ ("could not remove CHERRY_PICK_HEAD" )); -return 0 ; - } + is_clean = !has_uncommitted_changes (0 );if (file_exists (rebase_path_amend ())) {struct strbuf rev =STRBUF_INIT ;@@ -2804,19 +2801,107 @@ static int commit_staged_changes(struct replay_opts *opts)if (get_oid_hex (rev.buf, &to_amend))return error (_ ("invalid contents: '%s'" ),rebase_path_amend ()); -if (oidcmp (&head, &to_amend)) +if (!is_clean &&oidcmp (&head, &to_amend))return error (_ ("\nYou have uncommitted changes in your " "working tree. Please, commit them\n" "first and then run 'git rebase " "--continue' again." )); +/* +* When skipping a failed fixup/squash, we need to edit the +* commit message, the current fixup list and count, and if it +* was the last fixup/squash in the chain, we need to clean up +* the commit message and if there was a squash, let the user +* edit it. +*/ +if (is_clean && !oidcmp (&head, &to_amend) && + opts->current_fixup_count >0 && +file_exists (rebase_path_stopped_sha ())) { +const char *p = opts->current_fixups.buf; +int len = opts->current_fixups.len; + + opts->current_fixup_count--; +if (!len) +BUG ("Incorrect current_fixups:\n%s" , p); +while (len && p[len -1 ] !='\n' ) + len--; +strbuf_setlen (&opts->current_fixups, len); +if (write_message (p, len,rebase_path_current_fixups (), +0 ) <0 ) +return error (_ ("could not write file: '%s'" ), +rebase_path_current_fixups ()); + +/* +* If a fixup/squash in a fixup/squash chain failed, the +* commit message is already correct, no need to commit +* it again. +* +* Only if it is the final command in the fixup/squash +* chain, and only if the chain is longer than a single +* fixup/squash command (which was just skipped), do we +* actually need to re-commit with a cleaned up commit +* message. +*/ +if (opts->current_fixup_count >0 && + !is_fixup (peek_command (todo_list,0 ))) { + final_fixup =1 ; +/* +* If there was not a single "squash" in the +* chain, we only need to clean up the commit +* message, no need to bother the user with +* opening the commit message in the editor. +*/ +if (!starts_with (p,"squash " ) && + !strstr (p,"\nsquash " )) + flags = (flags & ~EDIT_MSG ) |CLEANUP_MSG ; + }else if (is_fixup (peek_command (todo_list,0 ))) { +/* +* We need to update the squash message to skip +* the latest commit message. +*/
sequencer.c static int commit_staged_changes(struct replay_opts *opts) · line 2870
Quoted 10 lines
sequencer.c +10
-0+struct commit *commit; +const char *path =rebase_path_squash_msg (); + +if (parse_head (&commit) || + !(p =get_commit_buffer (commit,NULL )) || +write_message (p,strlen (p), path,0 )) { +unuse_commit_buffer (commit, p); +return error (_ ("could not write file: " +"'%s'" ), path); + }
I think it should probably recreate the fixup message as well. If there is a sequence
pick commit
fixup a
fixup b
fixup c
and 'fixup b' gets skipped then when 'fixup c' is applied the user will be prompted to edit the message unless rebase_path_fixup_msg() exists.
Best Wishes
Phillip
Quoted 122 lines
sequencer.c +33
-5+unuse_commit_buffer (commit, p); + } + }strbuf_release (&rev); flags |=AMEND_MSG ; } -if (run_git_commit (rebase_path_message (), opts, flags)) +if (is_clean) { +const char *cherry_pick_head =git_path_cherry_pick_head (); + +if (file_exists (cherry_pick_head) &&unlink (cherry_pick_head)) +return error (_ ("could not remove CHERRY_PICK_HEAD" )); +if (!final_fixup) +return 0 ; + } + +if (run_git_commit (final_fixup ?NULL :rebase_path_message (), + opts, flags))return error (_ ("could not commit staged changes." ));unlink (rebase_path_amend ()); +if (final_fixup) { +unlink (rebase_path_fixup_msg ()); +unlink (rebase_path_squash_msg ()); + } +if (opts->current_fixup_count >0 ) { +/* +* Whether final fixup or not, we just cleaned up the commit +* message... +*/ +unlink (rebase_path_current_fixups ()); +strbuf_reset (&opts->current_fixups); + opts->current_fixup_count =0 ; + }return 0 ; }@@ -2828,14 +2913,16 @@ int sequencer_continue(struct replay_opts *opts)if (read_and_refresh_cache (opts))return -1 ; +if (read_populate_opts (opts)) +return -1 ;if (is_rebase_i (opts)) { -if (commit_staged_changes (opts)) +if ((res =read_populate_todo (&todo_list, opts))) + goto release_todo_list; +if (commit_staged_changes (opts, &todo_list))return -1 ; }else if (!file_exists (get_todo_path (opts)))return continue_single_pick (); -if (read_populate_opts (opts)) -return -1 ; -if ((res =read_populate_todo (&todo_list, opts))) +else if ((res =read_populate_todo (&todo_list, opts))) goto release_todo_list;if (!is_rebase_i (opts)) {t/t3418-rebase-continue.sh +31
-4@@ -88,14 +88,14 @@ test_expect_success 'rebase passes merge strategy options correctly' ' git rebase --continue ' -test_expect_failure '--skip after failed fixup cleans commit message' ' +test_expect_success '--skip after failed fixup cleans commit message' ' test_when_finished "test_might_fail git rebase --abort" && git checkout -b with-conflicting-fixup && test_commit wants-fixup && test_commit "fixup! wants-fixup" wants-fixup.t 1 wants-fixup-1 && test_commit "fixup! wants-fixup" wants-fixup.t 2 wants-fixup-2 && test_commit "fixup! wants-fixup" wants-fixup.t 3 wants-fixup-3 && - test_must_fail env FAKE_LINES="1 fixup 2 fixup 4" \ + test_must_fail env FAKE_LINES="1 fixup 2 squash 4" \ git rebase -i HEAD~4 && : now there is a conflict, and comments in the commit message &&@@ -103,11 +103,38 @@ test_expect_failure '--skip after failed fixup cleans commit message' ' grep "fixup! wants-fixup" out && : skip and continue && - git rebase --skip && + echo "cp \"\$1\" .git/copy.txt" | write_script copy-editor.sh && + (test_set_editor "$PWD/copy-editor.sh" && git rebase --skip) && + + : the user should not have had to edit the commit message && + test_path_is_missing .git/copy.txt && : now the comments in the commit message should have been cleaned up && git show HEAD >out && - ! grep "fixup! wants-fixup" out + ! grep "fixup! wants-fixup" out && + + : now, let us ensure that "squash" is handled correctly && + git reset --hard wants-fixup-3 && + test_must_fail env FAKE_LINES="1 squash 4 squash 2 squash 4" \ + git rebase -i HEAD~4 && + + : the first squash failed, but there are two more in the chain && + (test_set_editor "$PWD/copy-editor.sh" && + test_must_fail git rebase --skip) && + + : not the final squash, no need to edit the commit message && + test_path_is_missing .git/copy.txt && + + : The first squash was skipped, therefore: && + git show HEAD >out && + test_i18ngrep "# This is a combination of 2 commits" out && + + (test_set_editor "$PWD/copy-editor.sh" && git rebase --skip) && + git show HEAD >out && + test_i18ngrep ! "# This is a combination" out && + + : Final squash failed, but there was still a squash && + test_i18ngrep "# This is a combination of 2 commits" .git/copy.txt ' test_expect_success 'setup rerere database' '
Re: [PATCH v4 4/4] rebase --skip: clean up commit message after a failed fixup/squash
Quoted 148 lines · Phillip Wood
Hi Johannes, sorry it's taken me a while to look at this. I think it mostly makes sense to me, the code is well documented. I've got one comment below
Quoted 143 lines · Johannes Schindelin
During a series of fixup/squash commands, the interactive rebase builds up a commit message with comments. This will be presented to the user in the editor if at least one of those commands was a
squash.In any case, the commit message will be cleaned up eventually, removing all those intermediate comments, in the final step of such a fixup/squash chain.
However, if the last fixup/squash command in such a chain fails with merge conflicts, and if the user then decides to skip it (or resolve it to a clean worktree and then continue the rebase), the current code fails to clean up the commit message.
This commit fixes that behavior.
The fix is quite a bit more involved than meets the eye because it is not only about the question whether we are
git rebase --skiping a fixup or squash. It is also about removing the skipped fixup/squash's commit message from the accumulated commit message. And it is also about the question whether we should let the user edit the final commit message or not ("Was there a squash in the chain *that was not skipped*?").For example, in this case we will want to fix the commit message, but not open it in an editor:
pick <- succeeds
fixup <- succeeds
squash <- fails, will be skippedThis is where the newly-introduced
current-fixupsfile comes in real handy. A quick look and we can determine whether there was a non-skipped squash. We only need to make sure to keep it up to date with respect to skipped fixup/squash commands. As a bonus, we can even avoid committing unnecessarily, e.g. when there was only one fixup, and it failed, and was skipped.To fix only the bug where the final commit message was not cleaned up properly, but without fixing the rest, would have been more complicated than fixing it all in one go, hence this commit lumps together more than a single concern.
For the same reason, this commit also adds a bit more to the existing test case for the regression we just fixed.
The diff is best viewed with --color-moved.
Signed-off-by Johannes Schindelin <[email protected]>--- sequencer.c | 113 ++++++++++++++++++++++++++++++++----- t/t3418-rebase-continue.sh | 35 ++++++++++-- 2 files changed, 131 insertions(+), 17 deletions(-)sequencer.c +56
-8@@ -2779,19 +2779,16 @@ static int continue_single_pick(void)return run_command_v_opt (argv,RUN_GIT_CMD ); } -static int commit_staged_changes (struct replay_opts *opts) +static int commit_staged_changes (struct replay_opts *opts, +struct todo_list *todo_list) {unsigned int flags =ALLOW_EMPTY |EDIT_MSG ; +unsigned int final_fixup =0 , is_clean;if (has_unstaged_changes (1 ))return error (_ ("cannot rebase: You have unstaged changes." )); -if (!has_uncommitted_changes (0 )) { -const char *cherry_pick_head =git_path_cherry_pick_head (); -if (file_exists (cherry_pick_head) &&unlink (cherry_pick_head)) -return error (_ ("could not remove CHERRY_PICK_HEAD" )); -return 0 ; - } + is_clean = !has_uncommitted_changes (0 );if (file_exists (rebase_path_amend ())) {struct strbuf rev =STRBUF_INIT ;@@ -2804,19 +2801,107 @@ static int commit_staged_changes(struct replay_opts *opts)if (get_oid_hex (rev.buf, &to_amend))return error (_ ("invalid contents: '%s'" ),rebase_path_amend ()); -if (oidcmp (&head, &to_amend)) +if (!is_clean &&oidcmp (&head, &to_amend))return error (_ ("\nYou have uncommitted changes in your " "working tree. Please, commit them\n" "first and then run 'git rebase " "--continue' again." )); +/* +* When skipping a failed fixup/squash, we need to edit the +* commit message, the current fixup list and count, and if it +* was the last fixup/squash in the chain, we need to clean up +* the commit message and if there was a squash, let the user +* edit it. +*/ +if (is_clean && !oidcmp (&head, &to_amend) && + opts->current_fixup_count >0 && +file_exists (rebase_path_stopped_sha ())) { +const char *p = opts->current_fixups.buf; +int len = opts->current_fixups.len; + + opts->current_fixup_count--; +if (!len) +BUG ("Incorrect current_fixups:\n%s" , p); +while (len && p[len -1 ] !='\n' ) + len--; +strbuf_setlen (&opts->current_fixups, len); +if (write_message (p, len,rebase_path_current_fixups (), +0 ) <0 ) +return error (_ ("could not write file: '%s'" ), +rebase_path_current_fixups ()); + +/* +* If a fixup/squash in a fixup/squash chain failed, the +* commit message is already correct, no need to commit +* it again. +* +* Only if it is the final command in the fixup/squash +* chain, and only if the chain is longer than a single +* fixup/squash command (which was just skipped), do we +* actually need to re-commit with a cleaned up commit +* message. +*/ +if (opts->current_fixup_count >0 && + !is_fixup (peek_command (todo_list,0 ))) { + final_fixup =1 ; +/* +* If there was not a single "squash" in the +* chain, we only need to clean up the commit +* message, no need to bother the user with +* opening the commit message in the editor. +*/ +if (!starts_with (p,"squash " ) && + !strstr (p,"\nsquash " )) + flags = (flags & ~EDIT_MSG ) |CLEANUP_MSG ; + }else if (is_fixup (peek_command (todo_list,0 ))) { +/* +* We need to update the squash message to skip +* the latest commit message.
Quoted 8 lines
sequencer.c static int commit_staged_changes(struct replay_opts *opts) · line 2867
Quoted 8 lines
sequencer.c +8
-0+*/ +struct commit *commit; +const char *path =rebase_path_squash_msg (); + +if (parse_head (&commit) || + !(p =get_commit_buffer (commit,NULL )) || +write_message (p,strlen (p), path,0 )) { +unuse_commit_buffer (commit, p);
I forgot to mention last time that if parse_head() returns an error then commit is passed uninitialized to unuse_commit_buffer(). It also possible that p is not pointing to a commit buffer if git_commit_buffer() fails. Looking at the current implementation that is probably ok but it's a bit ugly and passing uninitialized variables around could cause problems in the future.
Quoted 142 lines
sequencer.c static int commit_staged_changes(struct replay_opts *opts) · line 2870
Quoted 3 lines
sequencer.c +3
-0+return error (_ ("could not write file: " +"'%s'" ), path); + }I think it should probably recreate the fixup message as well. If there is a sequence
pick commit
fixup a
fixup b
fixup cand 'fixup b' gets skipped then when 'fixup c' is applied the user will be prompted to edit the message unless
rebase_path_fixup_msg()exists.Best Wishes
Phillip
Quoted 122 lines
sequencer.c +33
-5+unuse_commit_buffer (commit, p); + } + }strbuf_release (&rev); flags |=AMEND_MSG ; } -if (run_git_commit (rebase_path_message (), opts, flags)) +if (is_clean) { +const char *cherry_pick_head =git_path_cherry_pick_head (); + +if (file_exists (cherry_pick_head) &&unlink (cherry_pick_head)) +return error (_ ("could not remove CHERRY_PICK_HEAD" )); +if (!final_fixup) +return 0 ; + } + +if (run_git_commit (final_fixup ?NULL :rebase_path_message (), + opts, flags))return error (_ ("could not commit staged changes." ));unlink (rebase_path_amend ()); +if (final_fixup) { +unlink (rebase_path_fixup_msg ()); +unlink (rebase_path_squash_msg ()); + } +if (opts->current_fixup_count >0 ) { +/* +* Whether final fixup or not, we just cleaned up the commit +* message... +*/ +unlink (rebase_path_current_fixups ()); +strbuf_reset (&opts->current_fixups); + opts->current_fixup_count =0 ; + }return 0 ; }@@ -2828,14 +2913,16 @@ int sequencer_continue(struct replay_opts *opts)if (read_and_refresh_cache (opts))return -1 ; +if (read_populate_opts (opts)) +return -1 ;if (is_rebase_i (opts)) { -if (commit_staged_changes (opts)) +if ((res =read_populate_todo (&todo_list, opts))) + goto release_todo_list; +if (commit_staged_changes (opts, &todo_list))return -1 ; }else if (!file_exists (get_todo_path (opts)))return continue_single_pick (); -if (read_populate_opts (opts)) -return -1 ; -if ((res =read_populate_todo (&todo_list, opts))) +else if ((res =read_populate_todo (&todo_list, opts))) goto release_todo_list;if (!is_rebase_i (opts)) {t/t3418-rebase-continue.sh +31
-4@@ -88,14 +88,14 @@ test_expect_success 'rebase passes merge strategy options correctly' ' git rebase --continue ' -test_expect_failure '--skip after failed fixup cleans commit message' ' +test_expect_success '--skip after failed fixup cleans commit message' ' test_when_finished "test_might_fail git rebase --abort" && git checkout -b with-conflicting-fixup && test_commit wants-fixup && test_commit "fixup! wants-fixup" wants-fixup.t 1 wants-fixup-1 && test_commit "fixup! wants-fixup" wants-fixup.t 2 wants-fixup-2 && test_commit "fixup! wants-fixup" wants-fixup.t 3 wants-fixup-3 && - test_must_fail env FAKE_LINES="1 fixup 2 fixup 4" \ + test_must_fail env FAKE_LINES="1 fixup 2 squash 4" \ git rebase -i HEAD~4 && : now there is a conflict, and comments in the commit message &&@@ -103,11 +103,38 @@ test_expect_failure '--skip after failed fixup cleans commit message' ' grep "fixup! wants-fixup" out && : skip and continue && - git rebase --skip && + echo "cp \"\$1\" .git/copy.txt" | write_script copy-editor.sh && + (test_set_editor "$PWD/copy-editor.sh" && git rebase --skip) && + + : the user should not have had to edit the commit message && + test_path_is_missing .git/copy.txt && : now the comments in the commit message should have been cleaned up && git show HEAD >out && - ! grep "fixup! wants-fixup" out + ! grep "fixup! wants-fixup" out && + + : now, let us ensure that "squash" is handled correctly && + git reset --hard wants-fixup-3 && + test_must_fail env FAKE_LINES="1 squash 4 squash 2 squash 4" \ + git rebase -i HEAD~4 && + + : the first squash failed, but there are two more in the chain && + (test_set_editor "$PWD/copy-editor.sh" && + test_must_fail git rebase --skip) && + + : not the final squash, no need to edit the commit message && + test_path_is_missing .git/copy.txt && + + : The first squash was skipped, therefore: && + git show HEAD >out && + test_i18ngrep "# This is a combination of 2 commits" out && + + (test_set_editor "$PWD/copy-editor.sh" && git rebase --skip) && + git show HEAD >out && + test_i18ngrep ! "# This is a combination" out && + + : Final squash failed, but there was still a squash && + test_i18ngrep "# This is a combination of 2 commits" .git/copy.txt ' test_expect_success 'setup rerere database' '
Re: [PATCH v4 4/4] rebase --skip: clean up commit message after a failed fixup/squash
In reply to Phillip WoodHi Phillip,
[sorry, I just got to this mail now]
Quoted 136 lines · Phillip Wood
Quoted 121 lines · Johannes Schindelin
During a series of fixup/squash commands, the interactive rebase builds up a commit message with comments. This will be presented to the user in the editor if at least one of those commands was a
squash.In any case, the commit message will be cleaned up eventually, removing all those intermediate comments, in the final step of such a fixup/squash chain.
However, if the last fixup/squash command in such a chain fails with merge conflicts, and if the user then decides to skip it (or resolve it to a clean worktree and then continue the rebase), the current code fails to clean up the commit message.
This commit fixes that behavior.
The fix is quite a bit more involved than meets the eye because it is not only about the question whether we are
git rebase --skiping a fixup or squash. It is also about removing the skipped fixup/squash's commit message from the accumulated commit message. And it is also about the question whether we should let the user edit the final commit message or not ("Was there a squash in the chain *that was not skipped*?").For example, in this case we will want to fix the commit message, but not open it in an editor:
pick <- succeeds
fixup <- succeeds
squash <- fails, will be skippedThis is where the newly-introduced
current-fixupsfile comes in real handy. A quick look and we can determine whether there was a non-skipped squash. We only need to make sure to keep it up to date with respect to skipped fixup/squash commands. As a bonus, we can even avoid committing unnecessarily, e.g. when there was only one fixup, and it failed, and was skipped.To fix only the bug where the final commit message was not cleaned up properly, but without fixing the rest, would have been more complicated than fixing it all in one go, hence this commit lumps together more than a single concern.
For the same reason, this commit also adds a bit more to the existing test case for the regression we just fixed.
The diff is best viewed with --color-moved.
Signed-off-by Johannes Schindelin <[email protected]>--- sequencer.c | 113 ++++++++++++++++++++++++++++++++----- t/t3418-rebase-continue.sh | 35 ++++++++++-- 2 files changed, 131 insertions(+), 17 deletions(-)sequencer.c +53
-1@@ -2804,19 +2801,107 @@ static int commit_staged_changes(struct replay_opts *opts)if (get_oid_hex (rev.buf, &to_amend))return error (_ ("invalid contents: '%s'" ),rebase_path_amend ()); -if (oidcmp (&head, &to_amend)) +if (!is_clean &&oidcmp (&head, &to_amend))return error (_ ("\nYou have uncommitted changes in your " "working tree. Please, commit them\n" "first and then run 'git rebase " "--continue' again." )); +/* +* When skipping a failed fixup/squash, we need to edit the +* commit message, the current fixup list and count, and if it +* was the last fixup/squash in the chain, we need to clean up +* the commit message and if there was a squash, let the user +* edit it. +*/ +if (is_clean && !oidcmp (&head, &to_amend) && + opts->current_fixup_count >0 && +file_exists (rebase_path_stopped_sha ())) { +const char *p = opts->current_fixups.buf; +int len = opts->current_fixups.len; + + opts->current_fixup_count--; +if (!len) +BUG ("Incorrect current_fixups:\n%s" , p); +while (len && p[len -1 ] !='\n' ) + len--; +strbuf_setlen (&opts->current_fixups, len); +if (write_message (p, len,rebase_path_current_fixups (), +0 ) <0 ) +return error (_ ("could not write file: '%s'" ), +rebase_path_current_fixups ()); + +/* +* If a fixup/squash in a fixup/squash chain failed, the +* commit message is already correct, no need to commit +* it again. +* +* Only if it is the final command in the fixup/squash +* chain, and only if the chain is longer than a single +* fixup/squash command (which was just skipped), do we +* actually need to re-commit with a cleaned up commit +* message. +*/ +if (opts->current_fixup_count >0 && + !is_fixup (peek_command (todo_list,0 ))) { + final_fixup =1 ; +/* +* If there was not a single "squash" in the +* chain, we only need to clean up the commit +* message, no need to bother the user with +* opening the commit message in the editor. +*/ +if (!starts_with (p,"squash " ) && + !strstr (p,"\nsquash " )) + flags = (flags & ~EDIT_MSG ) |CLEANUP_MSG ; + }else if (is_fixup (peek_command (todo_list,0 ))) { +/* +* We need to update the squash message to skip +* the latest commit message. +*/ sequencer.c static int commit_staged_changes(struct replay_opts *opts) · line 2870
Quoted 10 lines
sequencer.c +10
-0+struct commit *commit; +const char *path =rebase_path_squash_msg (); + +if (parse_head (&commit) || + !(p =get_commit_buffer (commit,NULL )) || +write_message (p,strlen (p), path,0 )) { +unuse_commit_buffer (commit, p); +return error (_ ("could not write file: " +"'%s'" ), path); + }I think it should probably recreate the fixup message as well. If there is a sequence
Quoted 7 lines
pick commit
fixup a
fixup b
fixup cand 'fixup b' gets skipped then when 'fixup c' is applied the user will be prompted to edit the message unless
rebase_path_fixup_msg()exists.
I was already on my way to fix this when I encountered this mail 30 minutes ago, but when I tried to implement the regression test, I took a step back: apart from "disk full" and "pilot error", there is really no good reason for the message-squash file not being able to be written.
And in both cases, a benign git status will show the latest command, i.e. the one that failed.
In other words: I now deem this such a corner case that it is not worth spending more time on the error message than we already did...
Ciao,
Dscho
Quoted 129 lines
Best Wishes
Phillip
Quoted 122 lines
sequencer.c +33
-5+unuse_commit_buffer (commit, p); + } + }strbuf_release (&rev); flags |=AMEND_MSG ; } -if (run_git_commit (rebase_path_message (), opts, flags)) +if (is_clean) { +const char *cherry_pick_head =git_path_cherry_pick_head (); + +if (file_exists (cherry_pick_head) &&unlink (cherry_pick_head)) +return error (_ ("could not remove CHERRY_PICK_HEAD" )); +if (!final_fixup) +return 0 ; + } + +if (run_git_commit (final_fixup ?NULL :rebase_path_message (), + opts, flags))return error (_ ("could not commit staged changes." ));unlink (rebase_path_amend ()); +if (final_fixup) { +unlink (rebase_path_fixup_msg ()); +unlink (rebase_path_squash_msg ()); + } +if (opts->current_fixup_count >0 ) { +/* +* Whether final fixup or not, we just cleaned up the commit +* message... +*/ +unlink (rebase_path_current_fixups ()); +strbuf_reset (&opts->current_fixups); + opts->current_fixup_count =0 ; + }return 0 ; }@@ -2828,14 +2913,16 @@ int sequencer_continue(struct replay_opts *opts)if (read_and_refresh_cache (opts))return -1 ; +if (read_populate_opts (opts)) +return -1 ;if (is_rebase_i (opts)) { -if (commit_staged_changes (opts)) +if ((res =read_populate_todo (&todo_list, opts))) + goto release_todo_list; +if (commit_staged_changes (opts, &todo_list))return -1 ; }else if (!file_exists (get_todo_path (opts)))return continue_single_pick (); -if (read_populate_opts (opts)) -return -1 ; -if ((res =read_populate_todo (&todo_list, opts))) +else if ((res =read_populate_todo (&todo_list, opts))) goto release_todo_list;if (!is_rebase_i (opts)) {t/t3418-rebase-continue.sh +31
-4@@ -88,14 +88,14 @@ test_expect_success 'rebase passes merge strategy options correctly' ' git rebase --continue ' -test_expect_failure '--skip after failed fixup cleans commit message' ' +test_expect_success '--skip after failed fixup cleans commit message' ' test_when_finished "test_might_fail git rebase --abort" && git checkout -b with-conflicting-fixup && test_commit wants-fixup && test_commit "fixup! wants-fixup" wants-fixup.t 1 wants-fixup-1 && test_commit "fixup! wants-fixup" wants-fixup.t 2 wants-fixup-2 && test_commit "fixup! wants-fixup" wants-fixup.t 3 wants-fixup-3 && - test_must_fail env FAKE_LINES="1 fixup 2 fixup 4" \ + test_must_fail env FAKE_LINES="1 fixup 2 squash 4" \ git rebase -i HEAD~4 && : now there is a conflict, and comments in the commit message &&@@ -103,11 +103,38 @@ test_expect_failure '--skip after failed fixup cleans commit message' ' grep "fixup! wants-fixup" out && : skip and continue && - git rebase --skip && + echo "cp \"\$1\" .git/copy.txt" | write_script copy-editor.sh && + (test_set_editor "$PWD/copy-editor.sh" && git rebase --skip) && + + : the user should not have had to edit the commit message && + test_path_is_missing .git/copy.txt && : now the comments in the commit message should have been cleaned up && git show HEAD >out && - ! grep "fixup! wants-fixup" out + ! grep "fixup! wants-fixup" out && + + : now, let us ensure that "squash" is handled correctly && + git reset --hard wants-fixup-3 && + test_must_fail env FAKE_LINES="1 squash 4 squash 2 squash 4" \ + git rebase -i HEAD~4 && + + : the first squash failed, but there are two more in the chain && + (test_set_editor "$PWD/copy-editor.sh" && + test_must_fail git rebase --skip) && + + : not the final squash, no need to edit the commit message && + test_path_is_missing .git/copy.txt && + + : The first squash was skipped, therefore: && + git show HEAD >out && + test_i18ngrep "# This is a combination of 2 commits" out && + + (test_set_editor "$PWD/copy-editor.sh" && git rebase --skip) && + git show HEAD >out && + test_i18ngrep ! "# This is a combination" out && + + : Final squash failed, but there was still a squash && + test_i18ngrep "# This is a combination of 2 commits" .git/copy.txt ' test_expect_success 'setup rerere database' '
Re: [PATCH v4 4/4] rebase --skip: clean up commit message after a failed fixup/squash
Hi Johannes
Quoted 3 lines · Johannes Schindelin
Hi Phillip,
[sorry, I just got to this mail now]
Don't worry, I'm impressed you remembered it, I'd completely forgotten about it.
Quoted 144 lines · Phillip Wood
Quoted 142 lines · Johannes Schindelin
Quoted 121 lines
During a series of fixup/squash commands, the interactive rebase builds up a commit message with comments. This will be presented to the user in the editor if at least one of those commands was a
squash.In any case, the commit message will be cleaned up eventually, removing all those intermediate comments, in the final step of such a fixup/squash chain.
However, if the last fixup/squash command in such a chain fails with merge conflicts, and if the user then decides to skip it (or resolve it to a clean worktree and then continue the rebase), the current code fails to clean up the commit message.
This commit fixes that behavior.
The fix is quite a bit more involved than meets the eye because it is not only about the question whether we are
git rebase --skiping a fixup or squash. It is also about removing the skipped fixup/squash's commit message from the accumulated commit message. And it is also about the question whether we should let the user edit the final commit message or not ("Was there a squash in the chain *that was not skipped*?").For example, in this case we will want to fix the commit message, but not open it in an editor:
pick <- succeeds
fixup <- succeeds
squash <- fails, will be skippedThis is where the newly-introduced
current-fixupsfile comes in real handy. A quick look and we can determine whether there was a non-skipped squash. We only need to make sure to keep it up to date with respect to skipped fixup/squash commands. As a bonus, we can even avoid committing unnecessarily, e.g. when there was only one fixup, and it failed, and was skipped.To fix only the bug where the final commit message was not cleaned up properly, but without fixing the rest, would have been more complicated than fixing it all in one go, hence this commit lumps together more than a single concern.
For the same reason, this commit also adds a bit more to the existing test case for the regression we just fixed.
The diff is best viewed with --color-moved.
Signed-off-by Johannes Schindelin <[email protected]>--- sequencer.c | 113 ++++++++++++++++++++++++++++++++----- t/t3418-rebase-continue.sh | 35 ++++++++++-- 2 files changed, 131 insertions(+), 17 deletions(-)sequencer.c +53
-1@@ -2804,19 +2801,107 @@ static int commit_staged_changes(struct replay_opts *opts)if (get_oid_hex (rev.buf, &to_amend))return error (_ ("invalid contents: '%s'" ),rebase_path_amend ()); -if (oidcmp (&head, &to_amend)) +if (!is_clean &&oidcmp (&head, &to_amend))return error (_ ("\nYou have uncommitted changes in your " "working tree. Please, commit them\n" "first and then run 'git rebase " "--continue' again." )); +/* +* When skipping a failed fixup/squash, we need to edit the +* commit message, the current fixup list and count, and if it +* was the last fixup/squash in the chain, we need to clean up +* the commit message and if there was a squash, let the user +* edit it. +*/ +if (is_clean && !oidcmp (&head, &to_amend) && + opts->current_fixup_count >0 && +file_exists (rebase_path_stopped_sha ())) { +const char *p = opts->current_fixups.buf; +int len = opts->current_fixups.len; + + opts->current_fixup_count--; +if (!len) +BUG ("Incorrect current_fixups:\n%s" , p); +while (len && p[len -1 ] !='\n' ) + len--; +strbuf_setlen (&opts->current_fixups, len); +if (write_message (p, len,rebase_path_current_fixups (), +0 ) <0 ) +return error (_ ("could not write file: '%s'" ), +rebase_path_current_fixups ()); + +/* +* If a fixup/squash in a fixup/squash chain failed, the +* commit message is already correct, no need to commit +* it again. +* +* Only if it is the final command in the fixup/squash +* chain, and only if the chain is longer than a single +* fixup/squash command (which was just skipped), do we +* actually need to re-commit with a cleaned up commit +* message. +*/ +if (opts->current_fixup_count >0 && + !is_fixup (peek_command (todo_list,0 ))) { + final_fixup =1 ; +/* +* If there was not a single "squash" in the +* chain, we only need to clean up the commit +* message, no need to bother the user with +* opening the commit message in the editor. +*/ +if (!starts_with (p,"squash " ) && + !strstr (p,"\nsquash " )) + flags = (flags & ~EDIT_MSG ) |CLEANUP_MSG ; + }else if (is_fixup (peek_command (todo_list,0 ))) { +/* +* We need to update the squash message to skip +* the latest commit message. +*/ sequencer.c static int commit_staged_changes(struct replay_opts *opts) · line 2870
Quoted 10 lines
sequencer.c +10
-0+struct commit *commit; +const char *path =rebase_path_squash_msg (); + +if (parse_head (&commit) || + !(p =get_commit_buffer (commit,NULL )) || +write_message (p,strlen (p), path,0 )) { +unuse_commit_buffer (commit, p); +return error (_ ("could not write file: " +"'%s'" ), path); + }I think it should probably recreate the fixup message as well. If there is a sequence
pick commit
fixup a
fixup b
fixup c
Quoted 7 lines
Quoted 2 lines
and 'fixup b' gets skipped then when 'fixup c' is applied the user will be prompted to edit the message unless
rebase_path_fixup_msg()exists.I was already on my way to fix this when I encountered this mail 30 minutes ago, but when I tried to implement the regression test, I took a step back: apart from "disk full" and "pilot error", there is really no good reason for the
message-squashfile not being able to be written.
Ah, I should perhaps have cut the patch a line higher to make it clearer I was not talking about the error condition. The code rewrites 'message-squash' to remove the commit message from the skipped fixup/squash. However if we have skipped a fixup and there are no preceding squash commands then when rebase stopped for the user to fix the merge conflicts it removed the 'message-fixup' file. I thought (and still think) it would be nice if 'rebase --skip' recreated the 'message-fixup' file so that the user is not unnecessarily prompted to edit the commit message at the end of the fixup chain but it's not the end of the world if it stays as it is now.
Best Wishes
Phillip
Quoted 139 lines
And in both cases, a benign
git statuswill show the latest command, i.e. the one that failed.In other words: I now deem this such a corner case that it is not worth spending more time on the error message than we already did...
Ciao,
DschoQuoted 129 lines
Best Wishes
Phillip
Quoted 122 lines
sequencer.c +33
-5+unuse_commit_buffer (commit, p); + } + }strbuf_release (&rev); flags |=AMEND_MSG ; } -if (run_git_commit (rebase_path_message (), opts, flags)) +if (is_clean) { +const char *cherry_pick_head =git_path_cherry_pick_head (); + +if (file_exists (cherry_pick_head) &&unlink (cherry_pick_head)) +return error (_ ("could not remove CHERRY_PICK_HEAD" )); +if (!final_fixup) +return 0 ; + } + +if (run_git_commit (final_fixup ?NULL :rebase_path_message (), + opts, flags))return error (_ ("could not commit staged changes." ));unlink (rebase_path_amend ()); +if (final_fixup) { +unlink (rebase_path_fixup_msg ()); +unlink (rebase_path_squash_msg ()); + } +if (opts->current_fixup_count >0 ) { +/* +* Whether final fixup or not, we just cleaned up the commit +* message... +*/ +unlink (rebase_path_current_fixups ()); +strbuf_reset (&opts->current_fixups); + opts->current_fixup_count =0 ; + }return 0 ; }@@ -2828,14 +2913,16 @@ int sequencer_continue(struct replay_opts *opts)if (read_and_refresh_cache (opts))return -1 ; +if (read_populate_opts (opts)) +return -1 ;if (is_rebase_i (opts)) { -if (commit_staged_changes (opts)) +if ((res =read_populate_todo (&todo_list, opts))) + goto release_todo_list; +if (commit_staged_changes (opts, &todo_list))return -1 ; }else if (!file_exists (get_todo_path (opts)))return continue_single_pick (); -if (read_populate_opts (opts)) -return -1 ; -if ((res =read_populate_todo (&todo_list, opts))) +else if ((res =read_populate_todo (&todo_list, opts))) goto release_todo_list;if (!is_rebase_i (opts)) {t/t3418-rebase-continue.sh +31
-4@@ -88,14 +88,14 @@ test_expect_success 'rebase passes merge strategy options correctly' ' git rebase --continue ' -test_expect_failure '--skip after failed fixup cleans commit message' ' +test_expect_success '--skip after failed fixup cleans commit message' ' test_when_finished "test_might_fail git rebase --abort" && git checkout -b with-conflicting-fixup && test_commit wants-fixup && test_commit "fixup! wants-fixup" wants-fixup.t 1 wants-fixup-1 && test_commit "fixup! wants-fixup" wants-fixup.t 2 wants-fixup-2 && test_commit "fixup! wants-fixup" wants-fixup.t 3 wants-fixup-3 && - test_must_fail env FAKE_LINES="1 fixup 2 fixup 4" \ + test_must_fail env FAKE_LINES="1 fixup 2 squash 4" \ git rebase -i HEAD~4 && : now there is a conflict, and comments in the commit message &&@@ -103,11 +103,38 @@ test_expect_failure '--skip after failed fixup cleans commit message' ' grep "fixup! wants-fixup" out && : skip and continue && - git rebase --skip && + echo "cp \"\$1\" .git/copy.txt" | write_script copy-editor.sh && + (test_set_editor "$PWD/copy-editor.sh" && git rebase --skip) && + + : the user should not have had to edit the commit message && + test_path_is_missing .git/copy.txt && : now the comments in the commit message should have been cleaned up && git show HEAD >out && - ! grep "fixup! wants-fixup" out + ! grep "fixup! wants-fixup" out && + + : now, let us ensure that "squash" is handled correctly && + git reset --hard wants-fixup-3 && + test_must_fail env FAKE_LINES="1 squash 4 squash 2 squash 4" \ + git rebase -i HEAD~4 && + + : the first squash failed, but there are two more in the chain && + (test_set_editor "$PWD/copy-editor.sh" && + test_must_fail git rebase --skip) && + + : not the final squash, no need to edit the commit message && + test_path_is_missing .git/copy.txt && + + : The first squash was skipped, therefore: && + git show HEAD >out && + test_i18ngrep "# This is a combination of 2 commits" out && + + (test_set_editor "$PWD/copy-editor.sh" && git rebase --skip) && + git show HEAD >out && + test_i18ngrep ! "# This is a combination" out && + + : Final squash failed, but there was still a squash && + test_i18ngrep "# This is a combination of 2 commits" .git/copy.txt ' test_expect_success 'setup rerere database' '
PATCH v7 8/17 sequencer: fast-forward `merge` commands, if possible
In reply to Johannes SchindelinJust like with regular pick commands, if we are trying to rebase a merge commit, we now test whether the parents of said commit match HEAD and the commits to be merged, and fast-forward if possible.
This is not only faster, but also avoids unnecessary proliferation of new objects.
--- sequencer.c | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-)
sequencer.c +32 -1
@@ -2679,7 +2679,7 @@ static int do_merge(struct commit *commit, const char *arg, int arg_len,struct commit *head_commit, *merge_commit, *i;struct commit_list *bases, *j, *reversed =NULL ;struct merge_options o; -int merge_arg_len, oneline_offset, ret; +int merge_arg_len, oneline_offset, can_fast_forward, ret;static struct lock_file lock;const char *p;
@@ -2764,6 +2764,37 @@ static int do_merge(struct commit *commit, const char *arg, int arg_len, } } +/* +* If HEAD is not identical to the first parent of the original merge +* commit, we cannot fast-forward. +*/ + can_fast_forward = opts->allow_ff && commit && commit->parents && + !oidcmp (&commit->parents->item->object.oid, + &head_commit->object.oid); + +/* +* If the merge head is different from the original one, we cannot +* fast-forward. +*/ +if (can_fast_forward) { +struct commit_list *second_parent = commit->parents->next; + +if (second_parent && !second_parent->next && +oidcmp (&merge_commit->object.oid, + &second_parent->item->object.oid)) + can_fast_forward =0 ; + } + +if (can_fast_forward && commit->parents->next && + !commit->parents->next->next && + !oidcmp (&commit->parents->next->item->object.oid, + &merge_commit->object.oid)) { +rollback_lock_file (&lock); + ret =fast_forward_to (&commit->object.oid, + &head_commit->object.oid,0 , opts); + goto leave_merge; + } +write_message (oid_to_hex (&merge_commit->object.oid),GIT_SHA1_HEXSZ ,git_path_merge_head (),0 );write_message ("no-ff" ,5 ,git_path_merge_mode (),0 );
Signature · 1 line
2.17.0.windows.1.4.g7e4058d72e3
PATCH v7 9/17 rebase-helper --make-script: introduce a flag to rebase merges
In reply to Johannes SchindelinThe sequencer just learned new commands intended to recreate branch structure (similar in spirit to --preserve-merges, but with a substantially less-broken design).
Let's allow the rebase--helper to generate todo lists making use of these commands, triggered by the new --rebase-merges option. For a commit topology like this (where the HEAD points to C):
- A - B - C \ / D
the generated todo list would look like this:
# branch D pick 0123 A label branch-point pick 1234 D label D
reset branch-point pick 2345 B merge -C 3456 D # C
To keep things simple, we first only implement support for merge commits with exactly two parents, leaving support for octopus merges to a later patch series.
As a special, hard-coded label, all merge-rebasing todo lists start with the command label onto so that we can later always refer to the revision onto which everything is rebased.
--- builtin/rebase--helper.c | 4 +- sequencer.c | 351 ++++++++++++++++++++++++++++++++++++++- sequencer.h | 1 + 3 files changed, 353 insertions(+), 3 deletions(-)
builtin/rebase--helper.c +3 -1
@@ -12,7 +12,7 @@ static const char * const builtin_rebase_helper_usage[] = {int cmd_rebase__helper (int argc,const char **argv,const char *prefix) {struct replay_opts opts =REPLAY_OPTS_INIT ; -unsigned flags =0 , keep_empty =0 ; +unsigned flags =0 , keep_empty =0 , rebase_merges =0 ;int abbreviate_commands =0 ;enum {CONTINUE =1 ,ABORT ,MAKE_SCRIPT ,SHORTEN_OIDS ,EXPAND_OIDS ,
@@ -24,6 +24,7 @@ int cmd_rebase__helper(int argc, const char **argv, const char *prefix)OPT_BOOL (0 ,"keep-empty" , &keep_empty,N_ ("keep empty commits" )),OPT_BOOL (0 ,"allow-empty-message" , &opts.allow_empty_message,N_ ("allow commits with empty messages" )), +OPT_BOOL (0 ,"rebase-merges" , &rebase_merges,N_ ("rebase merge commits" )),OPT_CMDMODE (0 ,"continue" , &command,N_ ("continue rebase" ),CONTINUE ), OPT_CMDMODE(0, "abort", &command, N_("abort rebase"),
@@ -57,6 +58,7 @@ int cmd_rebase__helper(int argc, const char **argv, const char *prefix) flags |= keep_empty ?TODO_LIST_KEEP_EMPTY :0 ; flags |= abbreviate_commands ?TODO_LIST_ABBREVIATE_CMDS :0 ; + flags |= rebase_merges ?TODO_LIST_REBASE_MERGES :0 ; flags |= command ==SHORTEN_OIDS ?TODO_LIST_SHORTEN_IDS :0 ;if (command ==CONTINUE && argc ==1 )
sequencer.c +349 -2
378 lines not on this page · raw message
sequencer.h +1 -0
@@ -59,6 +59,7 @@ int sequencer_remove_state(struct replay_opts *opts);#define TODO_LIST_KEEP_EMPTY (1U << 0)#define TODO_LIST_SHORTEN_IDS (1U << 1)#define TODO_LIST_ABBREVIATE_CMDS (1U << 2) +#define TODO_LIST_REBASE_MERGES (1U << 3)int sequencer_make_script (FILE *out,int argc,const char **argv,unsigned flags);
Signature · 1 line
2.17.0.windows.1.4.g7e4058d72e3
PATCH v7 10/17 rebase: introduce the --rebase-merges option
In reply to Johannes SchindelinOnce upon a time, this here developer thought: wouldn't it be nice if, say, Git for Windows' patches on top of core Git could be represented as a thicket of branches, and be rebased on top of core Git in order to maintain a cherry-pick'able set of patch series?
The original attempt to answer this was: git rebase --preserve-merges.
However, that experiment was never intended as an interactive option, and it only piggy-backed on git rebase --interactive because that command's implementation looked already very, very familiar: it was designed by the same person who designed --preserve-merges: yours truly.
Some time later, some other developer (I am looking at you, Andreas! ;-)) decided that it would be a good idea to allow --preserve-merges to be combined with --interactive (with caveats!) and the Git maintainer (well, the interim Git maintainer during Junio's absence, that is) agreed, and that is when the glamor of the --preserve-merges design started to fall apart rather quickly and unglamorously.
The reason? In --preserve-merges mode, the parents of a merge commit (or for that matter, of *any* commit) were not stated explicitly, but were *implied* by the commit name passed to the pick command.
This made it impossible, for example, to reorder commits. Not to mention to flatten the branch topology or, deity forbid, to split topic branches into two.
Alas, these shortcomings also prevented that mode (whose original purpose was to serve Git for Windows' needs, with the additional hope that it may be useful to others, too) from serving Git for Windows' needs.
Five years later, when it became really untenable to have one unwieldy, big hodge-podge patch series of partly related, partly unrelated patches in Git for Windows that was rebased onto core Git's tags from time to time (earning the undeserved wrath of the developer of the ill-fated git-remote-hg series that first obsoleted Git for Windows' competing approach, only to be abandoned without maintainer later) was really untenable, the "Git garden shears" were born [*1*/*2*]: a script, piggy-backing on top of the interactive rebase, that would first determine the branch topology of the patches to be rebased, create a pseudo todo list for further editing, transform the result into a real todo list (making heavy use of the exec command to "implement" the missing todo list commands) and finally recreate the patch series on top of the new base commit.
That was in 2013. And it took about three weeks to come up with the design and implement it as an out-of-tree script. Needless to say, the implementation needed quite a few years to stabilize, all the while the design itself proved itself sound.
With this patch, the goodness of the Git garden shears comes to git rebase -i itself. Passing the --rebase-merges option will generate a todo list that can be understood readily, and where it is obvious how to reorder commits. New branches can be introduced by inserting label commands and calling merge <label>. And once this mode will have become stable and universally accepted, we can deprecate the design mistake that was --preserve-merges.
Link *1*:
https://github.com/msysgit/msysgit/blob/master/share/msysGit/shears.sh
Link *2*:
https://github.com/git-for-windows/build-extra/blob/master/shears.sh
--- Documentation/git-rebase.txt | 10 +- contrib/completion/git-completion.bash | 2 +- git-rebase--interactive.sh | 1 + git-rebase.sh | 6 + t/t3430-rebase-merges.sh | 156 +++++++++++++++++++++++++ 5 files changed, 173 insertions(+), 2 deletions(-) create mode 100755 t/t3430-rebase-merges.sh
Documentation/git-rebase.txt +9 -1
@@ -378,6 +378,13 @@ The commit list format can be changed by setting the configuration option rebase.instructionFormat. A customized instruction format will automatically have the long commit hash prepended to the format. +-r:: +--rebase-merges:: + Rebase merge commits instead of flattening the history by replaying + merges. Merge conflict resolutions or manual amendments to merge + commits are not rebased automatically, but have to be applied + manually. + -p:: --preserve-merges:: Recreate merge commits instead of flattening the history by replaying
@@ -780,7 +787,8 @@ BUGS The todo list presented by `--preserve-merges --interactive` does not represent the topology of the revision graph. Editing commits and rewording their commit messages should work fine, but attempts to -reorder commits tend to produce counterintuitive results. +reorder commits tend to produce counterintuitive results. Use +--rebase-merges for a more faithful representation. For example, an attempt to rearrange ------------
contrib/completion/git-completion.bash +1 -1
@@ -1949,7 +1949,7 @@ _git_rebase () --*) __gitcomp " --onto --merge --strategy --interactive - --preserve-merges --stat --no-stat + --rebase-merges --preserve-merges --stat --no-stat --committer-date-is-author-date --ignore-date --ignore-whitespace --whitespace= --autosquash --no-autosquash
git-rebase--interactive.sh +1 -0
@@ -970,6 +970,7 @@ git_rebase__interactive () { init_revisions_and_shortrevisions git rebase--helper --make-script ${keep_empty:+--keep-empty} \ + ${rebase_merges:+--rebase-merges} \ $revisions ${restrict_revision+^$restrict_revision} >"$todo" || die "$(gettext "Could not generate todo list")"
git-rebase.sh +6 -0
@@ -17,6 +17,7 @@ q,quiet! be quiet. implies --no-stat autostash automatically stash/stash pop before and after fork-point use 'merge-base --fork-point' to refine upstream onto=! rebase onto given branch instead of upstream +r,rebase-merges! try to rebase merges instead of skipping them p,preserve-merges! try to recreate merges instead of ignoring them s,strategy=! use the given merge strategy no-ff! cherry-pick all commits, even if unchanged
@@ -88,6 +89,7 @@ type= state_dir= # One of {'', continue, skip, abort}, as parsed from command line action= +rebase_merges= preserve_merges= autosquash= keep_empty=
@@ -270,6 +272,10 @@ do --allow-empty-message) allow_empty_message=--allow-empty-message ;; + --rebase-merges) + rebase_merges=t + test -z "$interactive_rebase" && interactive_rebase=implied + ;; --preserve-merges) preserve_merges=t test -z "$interactive_rebase" && interactive_rebase=implied
t/t3430-rebase-merges.sh new file +156 -0
156 lines not on this page · raw message
Signature · 1 line
2.17.0.windows.1.4.g7e4058d72e3
PATCH v7 11/17 rebase --rebase-merges: add test for --keep-empty
In reply to Johannes SchindelinFrom: Phillip Wood <[email protected]>
If there are empty commits on the left hand side of $upstream...HEAD then the empty commits on the right hand side that we want to keep are being pruned.
--- t/t3421-rebase-topology-linear.sh | 1 + 1 file changed, 1 insertion(+)
t/t3421-rebase-topology-linear.sh +1 -0
@@ -217,6 +217,7 @@ test_run_rebase success '' test_run_rebase failure -m test_run_rebase failure -i test_run_rebase failure -p +test_run_rebase success --rebase-merges # m # /
Signature · 1 line
2.17.0.windows.1.4.g7e4058d72e3
PATCH v7 12/17 sequencer: make refs generated by the `label` command worktree-local
In reply to Johannes SchindelinThis allows for rebases to be run in parallel in separate worktrees (think: interrupted in the middle of one rebase, being asked to perform a different rebase, adding a separate worktree just for that job).
--- refs.c | 3 ++- t/t3430-rebase-merges.sh | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-)
refs.c +2 -1
@@ -600,7 +600,8 @@ int dwim_log(const char *str, int len, struct object_id *oid, char **log)static int is_per_worktree_ref (const char *refname) {return !strcmp (refname,"HEAD" ) || -starts_with (refname,"refs/bisect/" ); +starts_with (refname,"refs/bisect/" ) || +starts_with (refname,"refs/rewritten/" ); }static int is_pseudoref_syntax (const char *refname)
t/t3430-rebase-merges.sh +14 -0
@@ -153,4 +153,18 @@ test_expect_success 'with a branch tip that was cherry-picked already' ' EOF ' +test_expect_success 'refs/rewritten/* is worktree-local' ' + git worktree add wt && + cat >wt/script-from-scratch <<-\EOF && + label xyz + exec GIT_DIR=../.git git rev-parse --verify refs/rewritten/xyz >a || : + exec git rev-parse --verify refs/rewritten/xyz >b + EOF + + test_config -C wt sequence.editor \""$PWD"/replace-editor.sh\" && + git -C wt rebase -i HEAD && + test_must_be_empty wt/a && + test_cmp_rev HEAD "$(cat wt/b)" +' + test_done
Signature · 1 line
2.17.0.windows.1.4.g7e4058d72e3
PATCH v7 13/17 sequencer: handle post-rewrite for merge commands
In reply to Johannes SchindelinIn the previous patches, we implemented the basic functionality of the git rebase -i --rebase-merges command, in particular the merge command to create merge commits in the sequencer.
The interactive rebase is a lot more these days, though, than a simple cherry-pick in a loop. For example, it calls the post-rewrite hook (if any) after rebasing with a mapping of the old->new commits.
This patch implements the post-rewrite handling for the merge command we just introduced. The other commands that were added recently (label and reset) do not create new commits, therefore post-rewrite hooks do not need to handle them.
--- sequencer.c | 3 +++ t/t3430-rebase-merges.sh | 25 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+)
sequencer.c +3 -0
@@ -3061,6 +3061,9 @@ static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts) item->flags, opts);if (res <0 ) goto reschedule; +if (item->commit) +record_in_rewritten (&item->commit->object.oid, +peek_command (todo_list,1 )); }else if (!is_noop (item->command))return error (_ ("unknown command %d" ), item->command);
t/t3430-rebase-merges.sh +25 -0
@@ -167,4 +167,29 @@ test_expect_success 'refs/rewritten/* is worktree-local' ' test_cmp_rev HEAD "$(cat wt/b)" ' +test_expect_success 'post-rewrite hook and fixups work for merges' ' + git checkout -b post-rewrite && + test_commit same1 && + git reset --hard HEAD^ && + test_commit same2 && + git merge -m "to fix up" same1 && + echo same old same old >same2.t && + test_tick && + git commit --fixup HEAD same2.t && + fixup="$(git rev-parse HEAD)" && + + mkdir -p .git/hooks && + test_when_finished "rm .git/hooks/post-rewrite" && + echo "cat >actual" | write_script .git/hooks/post-rewrite && + + test_tick && + git rebase -i --autosquash -r HEAD^^^ && + printf "%s %s\n%s %s\n%s %s\n%s %s\n" >expect $(git rev-parse \ + $fixup^^2 HEAD^2 \ + $fixup^^ HEAD^ \ + $fixup^ HEAD \ + $fixup HEAD) && + test_cmp expect actual +' + test_done
Signature · 1 line
2.17.0.windows.1.4.g7e4058d72e3
PATCH v7 14/17 rebase --rebase-merges: avoid "empty merges"
In reply to Johannes SchindelinThe git merge command does not allow merging commits that are already reachable from HEAD: git merge HEAD^, for example, will report that we are already up to date and not change a thing.
In an interactive rebase, such a merge could occur previously, e.g. when competing (or slightly modified) versions of a patch series were applied upstream, and the user had to git rebase --skip all of the local commits, and the topic branch becomes "empty" as a consequence.
Let's teach the todo command merge to behave the same as git merge.
Seeing as it requires some low-level trickery to create such merges with Git's commands in the first place, we do not even have to bother to introduce an option to force merge to create such merge commits.
--- sequencer.c | 7 +++++++ t/t3430-rebase-merges.sh | 8 ++++++++ 2 files changed, 15 insertions(+)
sequencer.c +7 -0
@@ -2802,6 +2802,13 @@ static int do_merge(struct commit *commit, const char *arg, int arg_len,write_message ("no-ff" ,5 ,git_path_merge_mode (),0 ); bases =get_merge_bases (head_commit, merge_commit); +if (bases && !oidcmp (&merge_commit->object.oid, + &bases->item->object.oid)) { + ret =0 ; +/* skip merging an ancestor of HEAD */ + goto leave_merge; + } +for (j = bases; j; j = j->next)commit_list_insert (j->item, &reversed);free_commit_list (bases);
t/t3430-rebase-merges.sh +8 -0
@@ -192,4 +192,12 @@ test_expect_success 'post-rewrite hook and fixups work for merges' ' test_cmp expect actual ' +test_expect_success 'refuse to merge ancestors of HEAD' ' + echo "merge HEAD^" >script-from-scratch && + test_config -C wt sequence.editor \""$PWD"/replace-editor.sh\" && + before="$(git rev-parse HEAD)" && + git rebase -i HEAD && + test_cmp_rev HEAD $before +' + test_done
Signature · 1 line
2.17.0.windows.1.4.g7e4058d72e3
PATCH v7 15/17 pull: accept --rebase=merges to recreate the branch topology
In reply to Johannes SchindelinSimilar to the preserve mode simply passing the --preserve-merges option to the rebase command, the merges mode simply passes the --rebase-merges option.
This will allow users to conveniently rebase non-trivial commit topologies when pulling new commits, without flattening them.
--- Documentation/config.txt | 8 ++++++++ Documentation/git-pull.txt | 5 ++++- builtin/pull.c | 14 ++++++++++---- builtin/remote.c | 18 ++++++++++++++---- contrib/completion/git-completion.bash | 2 +- 5 files changed, 37 insertions(+), 10 deletions(-)
Documentation/config.txt +8 -0
@@ -1058,6 +1058,10 @@ branch.<name>.rebase:: "git pull" is run. See "pull.rebase" for doing this in a non branch-specific manner. + +When `merges`, pass the `--rebase-merges` option to 'git rebase' +so that locally committed merge commits will not be flattened +by running 'git pull'. ++ When preserve, also pass `--preserve-merges` along to 'git rebase' so that locally committed merge commits will not be flattened by running 'git pull'.
@@ -2617,6 +2621,10 @@ pull.rebase:: pull" is run. See "branch.<name>.rebase" for setting this on a per-branch basis. + +When `merges`, pass the `--rebase-merges` option to 'git rebase' +so that locally committed merge commits will not be flattened +by running 'git pull'. ++ When preserve, also pass `--preserve-merges` along to 'git rebase' so that locally committed merge commits will not be flattened by running 'git pull'.
Documentation/git-pull.txt +4 -1
@@ -101,13 +101,16 @@ Options related to merging include::merge-options.txt[] -r:: ---rebase[=false|true|preserve|interactive]:: +--rebase[=false|true|merges|preserve|interactive]:: When true, rebase the current branch on top of the upstream branch after fetching. If there is a remote-tracking branch corresponding to the upstream branch and the upstream branch was rebased since last fetched, the rebase uses that information to avoid rebasing non-local changes. + +When set to `merges`, rebase using `git rebase --rebase-merges` so that +locally created merge commits will not be flattened. ++ When set to preserve, rebase with the `--preserve-merges` option passed to `git rebase` so that locally created merge commits will not be flattened. +
builtin/pull.c +10 -4
@@ -27,14 +27,16 @@ enum rebase_type {REBASE_FALSE =0 ,REBASE_TRUE ,REBASE_PRESERVE , +REBASE_MERGES , REBASE_INTERACTIVE };/** * Parses the value of --rebase. If value is a false value, returns * REBASE_FALSE. If value is a true value, returns REBASE_TRUE. If value is -* "preserve", returns REBASE_PRESERVE. If value is a invalid value, dies with -* a fatal error if fatal is true, otherwise returns REBASE_INVALID. +* "merges", returns REBASE_MERGES. If value is "preserve", returns +* REBASE_PRESERVE. If value is a invalid value, dies with a fatal error if +* fatal is true, otherwise returns REBASE_INVALID. */ static enum rebase_type parse_config_rebase (const char *key,const char *value,int fatal)
@@ -47,6 +49,8 @@ static enum rebase_type parse_config_rebase(const char *key, const char *value,return REBASE_TRUE ; else if (!strcmp(value, "preserve"))return REBASE_PRESERVE ; + else if (!strcmp(value, "merges")) +return REBASE_MERGES ; else if (!strcmp(value, "interactive"))return REBASE_INTERACTIVE ;
@@ -130,7 +134,7 @@ static struct option pull_options[] = {/* Options passed to git-merge or git-rebase */ OPT_GROUP (N_ ("Options related to merging" )), { OPTION_CALLBACK, 'r', "rebase", &opt_rebase, -"false|true|preserve|interactive" , +"false|true|merges|preserve|interactive" ,N_ ("incorporate changes by rebasing rather than merging" ), PARSE_OPT_OPTARG, parse_opt_rebase }, OPT_PASSTHRU('n', NULL, &opt_diffstat, NULL,
@@ -800,7 +804,9 @@ static int run_rebase(const struct object_id *curr_head,argv_push_verbosity (&args);/* Options passed to git-rebase */ -if (opt_rebase ==REBASE_PRESERVE ) +if (opt_rebase ==REBASE_MERGES ) +argv_array_push (&args,"--rebase-merges" ); +else if (opt_rebase ==REBASE_PRESERVE )argv_array_push (&args,"--preserve-merges" );else if (opt_rebase ==REBASE_INTERACTIVE )argv_array_push (&args,"--interactive" );
builtin/remote.c +14 -4
@@ -245,7 +245,9 @@ static int add(int argc, const char **argv)struct branch_info {char *remote_name;struct string_list merge; -enum {NO_REBASE ,NORMAL_REBASE ,INTERACTIVE_REBASE } rebase; +enum { +NO_REBASE ,NORMAL_REBASE ,INTERACTIVE_REBASE ,REBASE_MERGES + } rebase; };static struct string_list branch_list =STRING_LIST_INIT_NODUP ;
@@ -306,6 +308,8 @@ static int config_read_branches(const char *key, const char *value, void *cb) info->rebase = v; else if (!strcmp(value, "preserve")) info->rebase =NORMAL_REBASE ; + else if (!strcmp(value, "merges")) + info->rebase =REBASE_MERGES ; else if (!strcmp(value, "interactive")) info->rebase =INTERACTIVE_REBASE ; }
@@ -963,9 +967,15 @@ static int show_local_info_item(struct string_list_item *item, void *cb_data)printf (" %-*s " , show_info->width, item->string);if (branch_info->rebase) { -printf_ln (branch_info->rebase ==INTERACTIVE_REBASE - ?_ ("rebases interactively onto remote %s" ) - :_ ("rebases onto remote %s" ), merge->items[0 ].string); +const char *msg; +if (branch_info->rebase ==INTERACTIVE_REBASE ) + msg =_ ("rebases interactively onto remote %s" ); +else if (branch_info->rebase ==REBASE_MERGES ) + msg =_ ("rebases interactively (with merges) onto " +"remote %s" ); +else + msg =_ ("rebases onto remote %s" ); +printf_ln (msg, merge->items[0 ].string);return 0 ; }else if (show_info->any_rebase) {printf_ln (_ (" merges with remote %s" ), merge->items[0 ].string);
contrib/completion/git-completion.bash +1 -1
@@ -2120,7 +2120,7 @@ _git_config () return ;; branch.*.rebase) - __gitcomp "false true preserve interactive" + __gitcomp "false true merges preserve interactive" return ;; remote.pushdefault)
Signature · 1 line
2.17.0.windows.1.4.g7e4058d72e3
PATCH v7 16/17 rebase -i: introduce --rebase-merges=[no-]rebase-cousins
In reply to Johannes SchindelinThis one is a bit tricky to explain, so let's try with a diagram:
C
/ \A - B - E - F
\ /
D
To illustrate what this new mode is all about, let's consider what happens upon git rebase -i --rebase-merges B, in particular to the commit D. So far, the new branch structure would be:
--- C' --
/ \
A - B ------ E' - F'
\ /
D'This is not really preserving the branch topology from before! The reason is that the commit D does not have B as ancestor, and therefore it gets rebased onto B.
This is unintuitive behavior. Even worse, when recreating branch structure, most use cases would appear to want cousins *not* to be rebased onto the new base commit. For example, Git for Windows (the heaviest user of the Git garden shears, which served as the blueprint for --rebase-merges) frequently merges branches from next early, and these branches certainly do *not* want to be rebased. In the example above, the desired outcome would look like this:
--- C' --
/ \A - B ------ E' - F'
\ /
-- D' --
Let's introduce the term "cousins" for such commits ("D" in the example), and let's not rebase them by default, introducing the new "rebase-cousins" mode for use cases where they should be rebased.
--- Documentation/git-rebase.txt | 7 ++++++- builtin/rebase--helper.c | 9 ++++++++- git-rebase--interactive.sh | 1 + git-rebase.sh | 12 +++++++++++- sequencer.c | 4 ++++ sequencer.h | 6 ++++++ t/t3430-rebase-merges.sh | 18 ++++++++++++++++++ 7 files changed, 54 insertions(+), 3 deletions(-)
Documentation/git-rebase.txt +6 -1
@@ -379,11 +379,16 @@ rebase.instructionFormat. A customized instruction format will automatically have the long commit hash prepended to the format. -r:: ---rebase-merges:: +--rebase-merges[=(rebase-cousins|no-rebase-cousins)]:: Rebase merge commits instead of flattening the history by replaying merges. Merge conflict resolutions or manual amendments to merge commits are not rebased automatically, but have to be applied manually. ++ +By default, or when `no-rebase-cousins` was specified, commits which do not +have `<upstream>` as direct ancestor will keep their original branch point. +If the `rebase-cousins` mode is turned on, such commits are rebased onto +`<upstream>` (or `<onto>`, if specified). -p:: --preserve-merges::
builtin/rebase--helper.c +8 -1
@@ -13,7 +13,7 @@ int cmd_rebase__helper(int argc, const char **argv, const char *prefix) {struct replay_opts opts =REPLAY_OPTS_INIT ;unsigned flags =0 , keep_empty =0 , rebase_merges =0 ; -int abbreviate_commands =0 ; +int abbreviate_commands =0 , rebase_cousins =-1 ;enum {CONTINUE =1 ,ABORT ,MAKE_SCRIPT ,SHORTEN_OIDS ,EXPAND_OIDS ,CHECK_TODO_LIST ,SKIP_UNNECESSARY_PICKS ,REARRANGE_SQUASH ,
@@ -25,6 +25,8 @@ int cmd_rebase__helper(int argc, const char **argv, const char *prefix)OPT_BOOL (0 ,"allow-empty-message" , &opts.allow_empty_message,N_ ("allow commits with empty messages" )),OPT_BOOL (0 ,"rebase-merges" , &rebase_merges,N_ ("rebase merge commits" )), +OPT_BOOL (0 ,"rebase-cousins" , &rebase_cousins, +N_ ("keep original branch points of cousins" )),OPT_CMDMODE (0 ,"continue" , &command,N_ ("continue rebase" ),CONTINUE ), OPT_CMDMODE(0, "abort", &command, N_("abort rebase"),
@@ -59,8 +61,13 @@ int cmd_rebase__helper(int argc, const char **argv, const char *prefix) flags |= keep_empty ?TODO_LIST_KEEP_EMPTY :0 ; flags |= abbreviate_commands ?TODO_LIST_ABBREVIATE_CMDS :0 ; flags |= rebase_merges ?TODO_LIST_REBASE_MERGES :0 ; + flags |= rebase_cousins >0 ?TODO_LIST_REBASE_COUSINS :0 ; flags |= command ==SHORTEN_OIDS ?TODO_LIST_SHORTEN_IDS :0 ; +if (rebase_cousins >=0 && !rebase_merges) +warning (_ ("--[no-]rebase-cousins has no effect without " +"--rebase-merges" )); +if (command ==CONTINUE && argc ==1 )return !!sequencer_continue (&opts);if (command ==ABORT && argc ==1 )
git-rebase--interactive.sh +1 -0
@@ -971,6 +971,7 @@ git_rebase__interactive () { git rebase--helper --make-script ${keep_empty:+--keep-empty} \ ${rebase_merges:+--rebase-merges} \ + ${rebase_cousins:+--rebase-cousins} \ $revisions ${restrict_revision+^$restrict_revision} >"$todo" || die "$(gettext "Could not generate todo list")"
git-rebase.sh +11 -1
@@ -17,7 +17,7 @@ q,quiet! be quiet. implies --no-stat autostash automatically stash/stash pop before and after fork-point use 'merge-base --fork-point' to refine upstream onto=! rebase onto given branch instead of upstream -r,rebase-merges! try to rebase merges instead of skipping them +r,rebase-merges? try to rebase merges instead of skipping them p,preserve-merges! try to recreate merges instead of ignoring them s,strategy=! use the given merge strategy no-ff! cherry-pick all commits, even if unchanged
@@ -90,6 +90,7 @@ state_dir= # One of {'', continue, skip, abort}, as parsed from command line action= rebase_merges= +rebase_cousins= preserve_merges= autosquash= keep_empty=
@@ -276,6 +277,15 @@ do rebase_merges=t test -z "$interactive_rebase" && interactive_rebase=implied ;; + --rebase-merges=*) + rebase_merges=t + case "${1#*=}" in + rebase-cousins) rebase_cousins=t;; + no-rebase-cousins) rebase_cousins=;; + *) die "Unknown mode: $1";; + esac + test -z "$interactive_rebase" && interactive_rebase=implied + ;; --preserve-merges) preserve_merges=t test -z "$interactive_rebase" && interactive_rebase=implied
sequencer.c +4 -0
@@ -3544,6 +3544,7 @@ static int make_script_with_merges(struct pretty_print_context *pp, unsigned flags) {int keep_empty = flags &TODO_LIST_KEEP_EMPTY ; +int rebase_cousins = flags &TODO_LIST_REBASE_COUSINS ;struct strbuf buf =STRBUF_INIT , oneline =STRBUF_INIT ;struct strbuf label =STRBUF_INIT ;struct commit_list *commits =NULL , **tail = &commits, *iter;
@@ -3721,6 +3722,9 @@ static int make_script_with_merges(struct pretty_print_context *pp, &commit->object.oid);if (entry) to = entry->string; +else if (!rebase_cousins) + to =label_oid (&commit->object.oid,NULL , + &state);if (!to || !strcmp (to,"onto" ))fprintf (out,"%s onto\n" , cmd_reset);
sequencer.h +6 -0
@@ -60,6 +60,12 @@ int sequencer_remove_state(struct replay_opts *opts);#define TODO_LIST_SHORTEN_IDS (1U << 1)#define TODO_LIST_ABBREVIATE_CMDS (1U << 2)#define TODO_LIST_REBASE_MERGES (1U << 3) +/* +* When rebasing merges, commits that do have the base commit as ancestor +* ("cousins") are *not* rebased onto the new base by default. If those +* commits should be rebased onto the new base, this flag needs to be passed. +*/ +#define TODO_LIST_REBASE_COUSINS (1U << 4)int sequencer_make_script (FILE *out,int argc,const char **argv,unsigned flags);
t/t3430-rebase-merges.sh +18 -0
@@ -153,6 +153,24 @@ test_expect_success 'with a branch tip that was cherry-picked already' ' EOF ' +test_expect_success 'do not rebase cousins unless asked for' ' + git checkout -b cousins master && + before="$(git rev-parse --verify HEAD)" && + test_tick && + git rebase -r HEAD^ && + test_cmp_rev HEAD $before && + test_tick && + git rebase --rebase-merges=rebase-cousins HEAD^ && + test_cmp_graph HEAD^.. <<-\EOF + * Merge the topic branch '\''onebranch'\'' + |\ + | * D + | * G + |/ + o H + EOF +' + test_expect_success 'refs/rewritten/* is worktree-local' ' git worktree add wt && cat >wt/script-from-scratch <<-\EOF &&
Signature · 1 line
2.17.0.windows.1.4.g7e4058d72e3
PATCH v7 17/17 rebase -i --rebase-merges: add a section to the man page
In reply to Johannes SchindelinThe --rebase-merges mode is probably not half as intuitive to use as its inventor hopes, so let's document it some.
--- Documentation/git-rebase.txt | 132 +++++++++++++++++++++++++++++++++++ 1 file changed, 132 insertions(+)
Documentation/git-rebase.txt +132 -0
@@ -389,6 +389,8 @@ By default, or when `no-rebase-cousins` was specified, commits which do not have `<upstream>` as direct ancestor will keep their original branch point. If the `rebase-cousins` mode is turned on, such commits are rebased onto `<upstream>` (or `<onto>`, if specified). ++ +See also REBASING MERGES below. -p:: --preserve-merges::
@@ -787,6 +789,136 @@ The ripple effect of a "hard case" recovery is especially bad: 'everyone' downstream from 'topic' will now have to perform a "hard case" recovery too! +REBASING MERGES +----------------- + +The interactive rebase command was originally designed to handle +individual patch series. As such, it makes sense to exclude merge +commits from the todo list, as the developer may have merged the +current `master` while working on the branch, only to eventually +rebase all the commits onto `master` (skipping the merge commits). + +However, there are legitimate reasons why a developer may want to +recreate merge commits: to keep the branch structure (or "commit +topology") when working on multiple, inter-related branches. + +In the following example, the developer works on a topic branch that +refactors the way buttons are defined, and on another topic branch +that uses that refactoring to implement a "Report a bug" button. The +output of `git log --graph --format=%s -5` may look like this: + +------------ +* Merge branch 'report-a-bug' +|\ +| * Add the feedback button +* | Merge branch 'refactor-button' +|\ \ +| |/ +| * Use the Button class for all buttons +| * Extract a generic Button class from the DownloadButton one +------------ + +The developer might want to rebase those commits to a newer `master` +while keeping the branch topology, for example when the first topic +branch is expected to be integrated into `master` much earlier than the +second one, say, to resolve merge conflicts with changes to the +DownloadButton class that made it into `master`. + +This rebase can be performed using the `--rebase-merges` option. +It will generate a todo list looking like this: + +------------ +label onto + +# Branch: refactor-button +reset onto +pick 123456 Extract a generic Button class from the DownloadButton one +pick 654321 Use the Button class for all buttons +label refactor-button + +# Branch: report-a-bug +reset refactor-button # Use the Button class for all buttons +pick abcdef Add the feedback button +label report-a-bug + +reset onto +merge -C a1b2c3 refactor-button # Merge 'refactor-button' +merge -C 6f5e4d report-a-bug # Merge 'report-a-bug' +------------ + +In contrast to a regular interactive rebase, there are `label`, `reset` and +`merge` commands in addition to `pick` ones. + +The `label` command associates a label with the current HEAD when that +command is executed. These labels are created as worktree-local refs +(`refs/rewritten/<label>`) that will be deleted when the rebase +finishes. That way, rebase operations in multiple worktrees linked to +the same repository do not interfere with one another. If the `label` command +fails, it is rescheduled immediately, with a helpful message how to proceed. + +The `reset` command is essentially a `git read-tree -m -u` (think: `git +reset --hard`, but refusing to overwrite untracked files) to the +specified revision (typically a previously-labeled one). If the `reset` +command fails, it is rescheduled immediately, with a helpful message how to +proceed. + +The `merge` command will merge the specified revision into whatever is +HEAD at that time. With `-C <original-commit>`, the commit message of +the specified merge commit will be used. When the `-C` is changed to +a lower-case `-c`, the message will be opened in an editor after a +successful merge so that the user can edit the message. + +If a `merge` command fails for any reason other than merge conflicts (i.e. +when the merge operation did not even start), it is rescheduled immediately. + +At this time, the `merge` command will *always* use the `recursive` +merge strategy, with no way to choose a different one. To work around +this, an `exec` command can be used to call `git merge` explicitly, +using the fact that the labels are worktree-local refs (the ref +`refs/rewritten/onto` would correspond to the label `onto`). + +Note: the first command (`label onto`) labels the revision onto which +the commits are rebased; The name `onto` is just a convention, as a nod +to the `--onto` option. + +It is also possible to introduce completely new merge commits from scratch +by adding a command of the form `merge <merge-head>`. This form will +generate a tentative commit message and always open an editor to let the +user edit it. This can be useful e.g. when a topic branch turns out to +address more than a single concern and wants to be split into two or +even more topic branches. Consider this todo list: + +------------ +pick 192837 Switch from GNU Makefiles to CMake +pick 5a6c7e Document the switch to CMake +pick 918273 Fix detection of OpenSSL in CMake +pick afbecd http: add support for TLS v1.3 +pick fdbaec Fix detection of cURL in CMake on Windows +------------ + +The one commit in this list that is not related to CMake may very well +have been motivated by working on fixing all those bugs introduced by +switching to CMake, but it addresses a different concern. To split this +branch into two topic branches, the todo list could be edited like this: + +------------ +label onto + +pick afbecd http: add support for TLS v1.3 +label tlsv1.3 + +reset onto +pick 192837 Switch from GNU Makefiles to CMake +pick 918273 Fix detection of OpenSSL in CMake +pick fdbaec Fix detection of cURL in CMake on Windows +pick 5a6c7e Document the switch to CMake +label cmake + +reset onto +merge tlsv1.3 +merge cmake +------------ + BUGS ---- The todo list presented by `--preserve-merges --interactive` does not
Signature · 1 line
2.17.0.windows.1.4.g7e4058d72e3
v8 cover rebase -i: offer to recreate commit topology by rebasing merges
In reply to Johannes SchindelinJunio, I think this is now ready for next. Thank you for your patience and help with this.
Once upon a time, I dreamed of an interactive rebase that would not linearize all patches and drop all merge commits, but instead recreate the commit topology faithfully.
My original attempt was --preserve-merges, but that design was so limited that I did not even enable it in interactive mode.
Subsequently, it *was* enabled in interactive mode, with the predictable
consequences: as the --preserve-merges design does not allow for specifying the parents of merge commits explicitly, all the new commits' parents are defined *implicitly* by the previous commit history, and hence it is *not possible to even reorder commits*.
This design flaw cannot be fixed. Not without a complete re-design, at least. This patch series offers such a re-design.
Think of --rebase-merges as "--preserve-merges done right". It introduces new verbs for the todo list, label, reset and merge. For a commit topology like this:
A - B - C
\ /
D
the generated todo list would look like this:
# branch D
pick 0123 A
label branch-point
pick 1234 D
label D reset branch-point
pick 2345 B
merge -C 3456 D # CThere are more patches in the pipeline, based on this patch series, but left for later in the interest of reviewable patch series: one mini series to use the sequencer even for git rebase -i --root, and another one to add support for octopus merges to --rebase-merges. And then one to allow for rebasing merge commits in a smarter way (this one will need a bit more work, though, as it can result in very complicated, nested merge conflicts *very* easily).
Changes since v7:
- Touched up all the documentation (it was a mistake to copy-edit the --preserve-merges description, for example).
- Disentangled the rescheduling of label/reset/merge from the one of the pick/fixup/squash code path (thanks Phillip!).
- When the merge failed, we now write out .git/rebase-merge/patch.
- An exec git cherry-pick or exec git revert will no longer mess with refs/rewritten/ in sequencer_remove_state() (d'oh....).
Johannes Schindelin (14):
sequencer: avoid using errno clobbered by rollback_lock_file()
sequencer: make rearrange_squash() a bit more obvious
sequencer: refactor how original todo list lines are accessed
sequencer: offer helpful advice when a command was rescheduled
sequencer: introduce the merge command
sequencer: fast-forward merge commands, if possible rebase-helper --make-script: introduce a flag to rebase merges
rebase: introduce the --rebase-merges option
sequencer: make refs generated by the label command worktree-local
sequencer: handle post-rewrite for merge commands
rebase --rebase-merges: avoid "empty merges"
pull: accept --rebase=merges to recreate the branch topology rebase -i: introduce --rebase-merges=[no-]rebase-cousins rebase -i --rebase-merges: add a section to the man page
Phillip Wood (1):
rebase --rebase-merges: add test for --keep-empty
Stefan Beller (1):
git-rebase--interactive: clarify arguments
Documentation/config.txt | 8 + Documentation/git-pull.txt | 6 +- Documentation/git-rebase.txt | 160 ++++- builtin/pull.c | 14 +- builtin/rebase--helper.c | 13 +- builtin/remote.c | 18 +- contrib/completion/git-completion.bash | 4 +- git-rebase--interactive.sh | 22 +- git-rebase.sh | 16 + refs.c | 3 +- sequencer.c | 891 +++++++++++++++++++++++-- sequencer.h | 7 + t/t3421-rebase-topology-linear.sh | 1 + t/t3430-rebase-merges.sh | 244 +++++++ 14 files changed, 1347 insertions(+), 60 deletions(-) create mode 100755 t/t3430-rebase-merges.sh
base-commit: fe0a9eaf31dd0c349ae4308498c33a5c3794b293
Published-As: https://github.com/dscho/git/releases/tag/recreate-merges-v8
Fetch-It-Via: git fetch https://github.com/dscho/git recreate-merges-v8
Interdiff vs v7:
diff --git a/Documentation/config.txt b/Documentation/config.txt index da46f154bb3..d6bcb5dcb67 100644
--- a/Documentation/config.txt
+++ b/Documentation/config.txt
@@ -1059,8 +1059,8 @@ branch.<name>.rebase::
branch-specific manner.
+
When merges, pass the --rebase-merges option to 'git rebase'
-so that locally committed merge commits will not be flattened -by running 'git pull'.
+so that the local merge commits are included in the rebase (see +linkgit:git-rebase[1] for details).
+
When preserve, also pass --preserve-merges along to 'git rebase' so that locally committed merge commits will not be flattened
@@ -2622,8 +2622,8 @@ pull.rebase::
per-branch basis.
+
When merges, pass the --rebase-merges option to 'git rebase'
-so that locally committed merge commits will not be flattened -by running 'git pull'.
+so that the local merge commits are included in the rebase (see +linkgit:git-rebase[1] for details).
+
When preserve, also pass --preserve-merges along to 'git rebase' so that locally committed merge commits will not be flattened
diff --git a/Documentation/git-pull.txt b/Documentation/git-pull.txt index 6f76d815dd3..4e0ad6fd8e0 100644
--- a/Documentation/git-pull.txt
+++ b/Documentation/git-pull.txt
@@ -109,7 +109,8 @@ include::merge-options.txt[]
to avoid rebasing non-local changes.
+
When set to merges, rebase using git rebase --rebase-merges so that
-locally created merge commits will not be flattened.
+the local merge commits are included in the rebase (see +linkgit:git-rebase[1] for details).
+
When set to preserve, rebase with the --preserve-merges option passed to git rebase so that locally created merge commits will not be flattened.
diff --git a/Documentation/git-rebase.txt b/Documentation/git-rebase.txt index 0ff83b62821..3b996e46d6a 100644
--- a/Documentation/git-rebase.txt
+++ b/Documentation/git-rebase.txt
@@ -380,15 +380,25 @@ have the long commit hash prepended to the format.
-r::
--rebase-merges[=(rebase-cousins|no-rebase-cousins)]::
- Rebase merge commits instead of flattening the history by replaying
- merges. Merge conflict resolutions or manual amendments to merge
- commits are not rebased automatically, but have to be applied
+ By default, a rebase will simply drop merge commits and only rebase
+ the non-merge commits. With this option, it will try to preserve
+ the branching structure within the commits that are to be rebased,
+ by recreating the merge commits. If a merge commit resolved any merge
+ or contained manual amendments, then they will have to be re-applied
manually.
+
By default, or when no-rebase-cousins was specified, commits which do not have <upstream> as direct ancestor will keep their original branch point.
-If the rebase-cousins mode is turned on, such commits are rebased onto -<upstream> (or <onto>, if specified).
+If the rebase-cousins mode is turned on, such commits are instead rebased +onto <upstream> (or <onto>, if specified).
++
+This mode is similar in spirit to --preserve-merges, but in contrast to +that option works well in interactive rebases: commits can be reordered, +inserted and dropped at will.
++
+It is currently only possible to recreate the merge commits using the +recursive merge strategy; Different merge strategies can be used only via +explicit exec git merge -s <strategy> [...] commands.
+
See also REBASING MERGES below.
@@ -795,8 +805,9 @@ REBASING MERGES
The interactive rebase command was originally designed to handle individual patch series. As such, it makes sense to exclude merge commits from the todo list, as the developer may have merged the
-current master while working on the branch, only to eventually -rebase all the commits onto master (skipping the merge commits). +then-current master while working on the branch, only to rebase +all the commits onto master eventually (skipping the merge +commits).
However, there are legitimate reasons why a developer may want to recreate merge commits: to keep the branch structure (or "commit
@@ -846,21 +857,23 @@ merge -C a1b2c3 refactor-button # Merge 'refactor-button'
merge -C 6f5e4d report-a-bug # Merge 'report-a-bug'
------------
-In contrast to a regular interactive rebase, there are label, reset and -merge commands in addition to pick ones.
+In contrast to a regular interactive rebase, there are label, reset +and merge commands in addition to pick ones.
The label command associates a label with the current HEAD when that command is executed. These labels are created as worktree-local refs (refs/rewritten/<label>) that will be deleted when the rebase finishes. That way, rebase operations in multiple worktrees linked to
-the same repository do not interfere with one another. If the label command -fails, it is rescheduled immediately, with a helpful message how to proceed. +the same repository do not interfere with one another. If the label +command fails, it is rescheduled immediately, with a helpful message how +to proceed.
-The reset command is essentially a git read-tree -m -u (think: git -reset --hard, but refusing to overwrite untracked files) to the -specified revision (typically a previously-labeled one). If the reset -command fails, it is rescheduled immediately, with a helpful message how to -proceed.
+The reset command resets the HEAD, index and worktree to the specified +revision. It is isimilar to an exec git reset --hard <label>, but +refuses to overwrite untracked files. If the reset command fails, it is +rescheduled immediately, with a helpful message how to edit the todo list +(this typically happens when a reset command was inserted into the todo +list manually and contains a typo).
The merge command will merge the specified revision into whatever is HEAD at that time. With -C <original-commit>, the commit message of
@@ -875,7 +888,7 @@ At this time, the merge command will *always* use the recursive
merge strategy, with no way to choose a different one. To work around this, an exec command can be used to call git merge explicitly, using the fact that the labels are worktree-local refs (the ref
-refs/rewritten/onto would correspond to the label onto). +refs/rewritten/onto would correspond to the label onto, for example).
Note: the first command (label onto) labels the revision onto which
the commits are rebased; The name onto is just a convention, as a nod
@@ -925,7 +938,7 @@ The todo list presented by --preserve-merges --interactive does not
represent the topology of the revision graph. Editing commits and rewording their commit messages should work fine, but attempts to
reorder commits tend to produce counterintuitive results. Use
---rebase-merges for a more faithful representation.
+--rebase-merges in such scenarios instead.
For example, an attempt to rearrange
------------
diff --git a/sequencer.c b/sequencer.c
index 3c7bb5d3fd8..9ffadbb3d3c 100644
--- a/sequencer.c
+++ b/sequencer.c
@@ -258,7 +258,8 @@ int sequencer_remove_state(struct replay_opts *opts)
struct strbuf buf = STRBUF_INIT;
int i;
- if (strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
+ if (is_rebase_i(opts) &&
+ strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
char *p = buf.buf;
while (*p) {
char *eol = strchr(p, '\n');
@@ -2960,7 +2961,7 @@ N_("Could not execute the todo command\n"
static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts) {
- int res = 0;
+ int res = 0, reschedule = 0;
setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
if (opts->allow_ff)
@@ -3002,7 +3003,7 @@ static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
res = do_pick_commit(item->command, item->commit,
opts, is_final_fixup(todo_list));
if (is_rebase_i(opts) && res < 0) {
-reschedule:
+ /* Reschedule */
advise(_(rescheduled_advice),
get_item_line_length(todo_list,
todo_list->current),
@@ -3059,21 +3060,42 @@ static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
}
} else if (item->command == TODO_LABEL) {
if ((res = do_label(item->arg, item->arg_len)))
- goto reschedule;
+ reschedule = 1;
} else if (item->command == TODO_RESET) {
if ((res = do_reset(item->arg, item->arg_len, opts)))
- goto reschedule;
+ reschedule = 1;
} else if (item->command == TODO_MERGE) {
- res = do_merge(item->commit, item->arg, item->arg_len,
- item->flags, opts);
- if (res < 0)
- goto reschedule;
- if (item->commit)
+ if ((res = do_merge(item->commit,
+ item->arg, item->arg_len,
+ item->flags, opts)) < 0)
+ reschedule = 1;
+ else if (item->commit)
record_in_rewritten(&item->commit->object.oid,
peek_command(todo_list, 1));
+ if (res > 0)
+ /* failed with merge conflicts */
+ return error_with_patch(item->commit,
+ item->arg,
+ item->arg_len, opts,
+ res, 0);
} else if (!is_noop(item->command))
return error(_("unknown command %d"), item->command);
+ if (reschedule) {
+ advise(_(rescheduled_advice),
+ get_item_line_length(todo_list, + todo_list->current), + get_item_line(todo_list, todo_list->current));
+ todo_list->current--;
+ if (save_todo(todo_list, opts))
+ return -1;
+ if (item->commit)
+ return error_with_patch(item->commit,
+ item->arg,
+ item->arg_len, opts,
+ res, 0);
+ }
+
todo_list->current++;
if (res)
return res;
diff --git a/t/t3430-rebase-merges.sh b/t/t3430-rebase-merges.sh
index f2de7059830..3d4dfdf7bec 100755
--- a/t/t3430-rebase-merges.sh
+++ b/t/t3430-rebase-merges.sh
@@ -125,6 +125,29 @@ test_expect_success 'reset refuses to overwrite untracked files' '
git rebase --abort
'
+test_expect_success 'failed merge writes patch (may be rescheduled, too)' '
+ test_when_finished "test_might_fail git rebase --abort" &&
+ git checkout -b conflicting-merge A &&
+
+ : fail because of conflicting untracked file &&
+ >G.t &&
+ echo "merge -C H G" >script-from-scratch &&
+ test_config sequence.editor \""$PWD"/replace-editor.sh\" &&
+ test_tick &&
+ test_must_fail git rebase -ir HEAD &&
+ grep "^merge -C .* G$" .git/rebase-merge/done &&
+ grep "^merge -C .* G$" .git/rebase-merge/git-rebase-todo &&
+ test_path_is_file .git/rebase-merge/patch &&
+
+ : fail because of merge conflict &&
+ rm G.t .git/rebase-merge/patch &&
+ git reset --hard &&
+ test_commit conflicting-G G.t not-G conflicting-G &&
+ test_must_fail git rebase --continue &&
+ ! grep "^merge -C .* G$" .git/rebase-merge/git-rebase-todo &&
+ test_path_is_file .git/rebase-merge/patch
+'
+
test_expect_success 'with a branch tip that was cherry-picked already' '
git checkout -b already-upstream master &&
base="$(git rev-parse --verify HEAD)" &&
Signature · 1 line
2.17.0.windows.1.15.gaa56ade3205
PATCH v8 1/16 sequencer: avoid using errno clobbered by rollback_lock_file()
As pointed out in a review of the --rebase-merges patch series, rollback_lock_file() clobbers errno. Therefore, we have to report the error message that uses errno before calling said function.
--- sequencer.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-)
sequencer.c +6 -4
@@ -345,12 +345,14 @@ static int write_message(const void *buf, size_t len, const char *filename,if (msg_fd <0 )return error_errno (_ ("could not lock '%s'" ), filename);if (write_in_full (msg_fd, buf, len) <0 ) { +error_errno (_ ("could not write to '%s'" ), filename);rollback_lock_file (&msg_file); -return error_errno (_ ("could not write to '%s'" ), filename); +return -1 ; }if (append_eol &&write (msg_fd,"\n" ,1 ) <0 ) { +error_errno (_ ("could not write eol to '%s'" ), filename);rollback_lock_file (&msg_file); -return error_errno (_ ("could not write eol to '%s'" ), filename); +return -1 ; }if (commit_lock_file (&msg_file) <0 )return error (_ ("failed to finalize '%s'" ), filename);
@@ -2119,9 +2121,9 @@ static int save_head(const char *head) written =write_in_full (fd, buf.buf, buf.len);strbuf_release (&buf);if (written <0 ) { +error_errno (_ ("could not write to '%s'" ),git_path_head_file ());rollback_lock_file (&head_lock); -return error_errno (_ ("could not write to '%s'" ), -git_path_head_file ()); +return -1 ; }if (commit_lock_file (&head_lock) <0 )return error (_ ("failed to finalize '%s'" ),git_path_head_file ());
Signature · 1 line
2.17.0.windows.1.15.gaa56ade3205
PATCH v8 2/16 sequencer: make rearrange_squash() a bit more obvious
In reply to Johannes SchindelinThere are some commands that have to be skipped from rearranging by virtue of not handling any commits.
However, the logic was not quite obvious: it skipped commands based on their position in the enum todo_command.
Instead, let's make it explicit that we skip all commands that do not handle any commit. With one exception: the drop command, because it, well, drops the commit and is therefore not eligible to rearranging.
Note: this is a bit academic at the moment because the only time we call rearrange_squash() is directly after generating the todo list, when we have nothing but pick commands anyway.
However, the upcoming merge command *will* want to be handled by that function, and it *can* handle commits.
--- sequencer.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
sequencer.c +1 -1
@@ -3393,7 +3393,7 @@ int rearrange_squash(void)struct subject2item_entry *entry; next[i] = tail[i] =-1 ; -if (item->command >=TODO_EXEC ) { +if (!item->commit || item->command ==TODO_DROP ) { subjects[i] =NULL ;continue ; }
Signature · 1 line
2.17.0.windows.1.15.gaa56ade3205
PATCH v8 3/16 sequencer: refactor how original todo list lines are accessed
In reply to Johannes SchindelinPreviously, we did a lot of arithmetic gymnastics to get at the line in the todo list (as stored in todo_list.buf). This might have been fast, but only in terms of execution speed, not in terms of developer time.
Let's refactor this to make it a lot easier to read, and hence to reason about the correctness of the code. It is not performance-critical code anyway.
--- sequencer.c | 60 ++++++++++++++++++++++++++++++++--------------------- 1 file changed, 36 insertions(+), 24 deletions(-)
sequencer.c +36 -24
@@ -1870,6 +1870,23 @@ static int count_commands(struct todo_list *todo_list)return count; } +static int get_item_line_offset (struct todo_list *todo_list,int index) +{ +return index < todo_list->nr ? + todo_list->items[index].offset_in_buf : todo_list->buf.len; +} + +static const char *get_item_line (struct todo_list *todo_list,int index) +{ +return todo_list->buf.buf +get_item_line_offset (todo_list, index); +} + +static int get_item_line_length (struct todo_list *todo_list,int index) +{ +return get_item_line_offset (todo_list, index +1 ) + -get_item_line_offset (todo_list, index); +} +static ssize_t strbuf_read_file_or_whine (struct strbuf *sb,const char *path) {int fd;
@@ -2244,29 +2261,27 @@ static int save_todo(struct todo_list *todo_list, struct replay_opts *opts) fd =hold_lock_file_for_update (&todo_lock, todo_path,0 );if (fd <0 )return error_errno (_ ("could not lock '%s'" ), todo_path); - offset = next < todo_list->nr ? - todo_list->items[next].offset_in_buf : todo_list->buf.len; + offset =get_item_line_offset (todo_list, next);if (write_in_full (fd, todo_list->buf.buf + offset, todo_list->buf.len - offset) <0 )return error_errno (_ ("could not write to '%s'" ), todo_path);if (commit_lock_file (&todo_lock) <0 )return error (_ ("failed to finalize '%s'" ), todo_path); -if (is_rebase_i (opts)) { -const char *done_path =rebase_path_done (); -int fd =open (done_path,O_CREAT |O_WRONLY |O_APPEND ,0666 ); -int prev_offset = !next ?0 : - todo_list->items[next -1 ].offset_in_buf; +if (is_rebase_i (opts) && next >0 ) { +const char *done =rebase_path_done (); +int fd =open (done,O_CREAT |O_WRONLY |O_APPEND ,0666 ); +int ret =0 ; -if (fd >=0 && offset > prev_offset && -write_in_full (fd, todo_list->buf.buf + prev_offset, - offset - prev_offset) <0 ) { -close (fd); -return error_errno (_ ("could not write to '%s'" ), - done_path); - } -if (fd >=0 ) -close (fd); +if (fd <0 ) +return 0 ; +if (write_in_full (fd,get_item_line (todo_list, next -1 ), +get_item_line_length (todo_list, next -1 )) + <0 ) + ret =error_errno (_ ("could not write to '%s'" ), done); +if (close (fd) <0 ) + ret =error_errno (_ ("failed to finalize '%s'" ), done); +return ret; }return 0 ; }
@@ -3297,8 +3312,7 @@ int skip_unnecessary_picks(void) oid = &item->commit->object.oid; }if (i >0 ) { -int offset = i < todo_list.nr ? - todo_list.items[i].offset_in_buf : todo_list.buf.len; +int offset =get_item_line_offset (&todo_list, i);const char *done_path =rebase_path_done (); fd =open (done_path,O_CREAT |O_WRONLY |O_APPEND ,0666 );
@@ -3478,12 +3492,10 @@ int rearrange_squash(void)continue ;while (cur >=0 ) { -int offset = todo_list.items[cur].offset_in_buf; -int end_offset = cur +1 < todo_list.nr ? - todo_list.items[cur +1 ].offset_in_buf : - todo_list.buf.len; -char *bol = todo_list.buf.buf + offset; -char *eol = todo_list.buf.buf + end_offset; +const char *bol = +get_item_line (&todo_list, cur); +const char *eol = +get_item_line (&todo_list, cur +1 );/* replace 'pick', by 'fixup' or 'squash' */ command = todo_list.items[cur].command;
Signature · 1 line
2.17.0.windows.1.15.gaa56ade3205
PATCH v8 4/16 sequencer: offer helpful advice when a command was rescheduled
In reply to Johannes SchindelinPreviously, we did that just magically, and potentially left some users quite puzzled. Let's err on the safe side instead, telling the user what is happening, and how they are supposed to continue.
--- sequencer.c | 16 ++++++++++++++++ 1 file changed, 16 insertions(+)
sequencer.c +16 -0
@@ -2555,6 +2555,17 @@ static const char *reflog_message(struct replay_opts *opts,return buf.buf; } +static const char rescheduled_advice[] = +N_ ("Could not execute the todo command\n" +"\n" +" %.*s" +"\n" +"It has been rescheduled; To edit the command before continuing, please\n" +"edit the todo list first:\n" +"\n" +" git rebase --edit-todo\n" +" git rebase --continue\n" ); +static int pick_commits (struct todo_list *todo_list,struct replay_opts *opts) {int res =0 ;
@@ -2600,6 +2611,11 @@ static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts) opts, is_final_fixup(todo_list));if (is_rebase_i (opts) && res <0 ) {/* Reschedule */ +advise (_ (rescheduled_advice), +get_item_line_length (todo_list, + todo_list->current), +get_item_line (todo_list, + todo_list->current)); todo_list->current--;if (save_todo (todo_list, opts))return -1 ;
Signature · 1 line
2.17.0.windows.1.15.gaa56ade3205
PATCH v8 5/16 git-rebase--interactive: clarify arguments
In reply to Johannes SchindelinFrom: Stefan Beller <[email protected]>
Up to now each command took a commit as its first argument and ignored the rest of the line (usually the subject of the commit)
Now that we are about to introduce commands that take different arguments, clarify each command by giving the argument list.
--- git-rebase--interactive.sh | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-)
git-rebase--interactive.sh +7 -7
@@ -155,13 +155,13 @@ reschedule_last_action () { append_todo_help () { gettext " Commands: -p, pick = use commit -r, reword = use commit, but edit the commit message -e, edit = use commit, but stop for amending -s, squash = use commit, but meld into previous commit -f, fixup = like \"squash\", but discard this commit's log message -x, exec = run command (the rest of the line) using shell -d, drop = remove commit +p, pick <commit> = use commit +r, reword <commit> = use commit, but edit the commit message +e, edit <commit> = use commit, but stop for amending +s, squash <commit> = use commit, but meld into previous commit +f, fixup <commit> = like \"squash\", but discard this commit's log message +x, exec <commit> = run command (the rest of the line) using shell +d, drop <commit> = remove commit These lines can be re-ordered; they are executed from top to bottom. " | git stripspace --comment-lines >>"$todo"
Signature · 1 line
2.17.0.windows.1.15.gaa56ade3205
PATCH v8 6/16 sequencer: introduce the `merge` command
In reply to Johannes SchindelinThis patch is part of the effort to reimplement --preserve-merges with a substantially improved design, a design that has been developed in the Git for Windows project to maintain the dozens of Windows-specific patch series on top of upstream Git.
The previous patch implemented the label and reset commands to label commits and to reset to labeled commits. This patch adds the merge command, with the following syntax:
merge [-C <commit>] <rev> # <oneline>
The <commit> parameter in this instance is the *original* merge commit, whose author and message will be used for the merge commit that is about to be created.
The <rev> parameter refers to the (possibly rewritten) revision to merge. Let's see an example of a todo list:
label onto
# Branch abc
reset onto
pick deadbeef Hello, world!
label abc
reset onto
pick cafecafe And now for something completely different merge -C baaabaaa abc # Merge the branch 'abc' into master
To edit the merge commit's message (a "reword" for merges, if you will), use -c (lower-case) instead of -C; this convention was borrowed from git commit that also supports -c and -C with similar meanings.
To create *new* merges, i.e. without copying the commit message from an existing commit, simply omit the -C <commit> parameter (which will open an editor for the merge message):
merge abc
This comes in handy when splitting a branch into two or more branches.
Note: this patch only adds support for recursive merges, to keep things simple. Support for octopus merges will be added later in a separate patch series, support for merges using strategies other than the recursive merge is left for the future.
--- git-rebase--interactive.sh | 6 + sequencer.c | 407 ++++++++++++++++++++++++++++++++++++- 2 files changed, 406 insertions(+), 7 deletions(-)
git-rebase--interactive.sh +6 -0
@@ -162,6 +162,12 @@ s, squash <commit> = use commit, but meld into previous commit f, fixup <commit> = like \"squash\", but discard this commit's log message x, exec <commit> = run command (the rest of the line) using shell d, drop <commit> = remove commit +l, label <label> = label current HEAD with a name +t, reset <label> = reset HEAD to a label +m, merge [-C <commit> | -c <commit>] <label> [# <oneline>] +. create a merge commit using the original merge commit's +. message (or the oneline, if no original merge commit was +. specified). Use -c <commit> to reword the commit message. These lines can be re-ordered; they are executed from top to bottom. " | git stripspace --comment-lines >>"$todo"
sequencer.c +400 -7
507 lines not on this page · raw message
Signature · 1 line
2.17.0.windows.1.15.gaa56ade3205
Re: [PATCH v8 06/16] sequencer: introduce the `merge` command
Quoted 8 lines · Johannes Schindelin
This patch is part of the effort to reimplement
--preserve-mergeswith a substantially improved design, a design that has been developed in the Git for Windows project to maintain the dozens of Windows-specific patch series on top of upstream Git.The previous patch implemented the
labelandresetcommands to label commits and to reset to labeled commits. This patch adds themergecommand, with the following syntax:
The two patches seem to have been fused together in this series.
If the reset command fails because it would overwrite untracked files it says
error: Untracked working tree file 'b' would be overwritten by merge.
Followed by the hint to edit the todo file. Saying 'merge' rather 'reset' is possibly confusing to users. Perhaps it could call setup_unpack_trees_porcelain(), though that would need to be extended to handle 'reset'. Also it currently refuses to overwrite ignored files which is either annoying or safe depending on one's point of view.
Best Wishes
Phillip
Quoted 586 lines
merge [-C <commit>] <rev> # <oneline>The <commit> parameter in this instance is the *original* merge commit, whose author and message will be used for the merge commit that is about to be created.
The <rev> parameter refers to the (possibly rewritten) revision to merge. Let's see an example of a todo list:
label onto
# Branch abc
reset onto
pick deadbeef Hello, world!
label abcreset onto
pick cafecafe And now for something completely different merge -C baaabaaa abc # Merge the branch 'abc' into masterTo edit the merge commit's message (a "reword" for merges, if you will), use
-c(lower-case) instead of-C; this convention was borrowed fromgit committhat also supports-cand-Cwith similar meanings.To create *new* merges, i.e. without copying the commit message from an existing commit, simply omit the
-C <commit>parameter (which will open an editor for the merge message):merge abc
This comes in handy when splitting a branch into two or more branches.
Note: this patch only adds support for recursive merges, to keep things simple. Support for octopus merges will be added later in a separate patch series, support for merges using strategies other than the recursive merge is left for the future.
Signed-off-by Johannes Schindelin <[email protected]>--- git-rebase--interactive.sh | 6 + sequencer.c | 407 ++++++++++++++++++++++++++++++++++++- 2 files changed, 406 insertions(+), 7 deletions(-)git-rebase--interactive.sh +6
-0@@ -162,6 +162,12 @@ s, squash <commit> = use commit, but meld into previous commit f, fixup <commit> = like \"squash\", but discard this commit's log message x, exec <commit> = run command (the rest of the line) using shell d, drop <commit> = remove commit +l, label <label> = label current HEAD with a name +t, reset <label> = reset HEAD to a label +m, merge [-C <commit> | -c <commit>] <label> [# <oneline>] +. create a merge commit using the original merge commit's +. message (or the oneline, if no original merge commit was +. specified). Use -c <commit> to reword the commit message. These lines can be re-ordered; they are executed from top to bottom. " | git stripspace --comment-lines >>"$todo"sequencer.c +400
-7@@ -23,6 +23,8 @@#include "hashmap.h" #include "notes-utils.h" #include "sigchain.h" +#include "unpack-trees.h" +#include "worktree.h" #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"@@ -120,6 +122,13 @@ static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha") static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list") staticGIT_PATH_FUNC (rebase_path_rewritten_pending,"rebase-merge/rewritten-pending" ) + +/* +* The path of the file listing refs that need to be deleted after the rebase +* finishes. This is used by the `label` command to record the need for cleanup. + */ +static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete") +/* * The following files are written by git-rebase just after parsing the * command-line (and are only consumed, not modified, by the sequencer). @@ -244,18 +253,34 @@ static const char *gpg_sign_opt_quoted(struct replay_opts *opts)int sequencer_remove_state (struct replay_opts *opts) { -struct strbuf dir =STRBUF_INIT ; +struct strbuf buf =STRBUF_INIT ;int i; +if (is_rebase_i (opts) && +strbuf_read_file (&buf,rebase_path_refs_to_delete (),0 ) >0 ) { +char *p = buf.buf; +while (*p) { +char *eol =strchr (p,'\n' ); +if (eol) + *eol ='\0' ; +if (delete_ref ("(rebase -i) cleanup" , p,NULL ,0 ) <0 ) +warning (_ ("could not delete '%s'" ), p); +if (!eol) +break ; + p = eol +1 ; + } + } +free (opts->gpg_sign);free (opts->strategy);for (i =0 ; i < opts->xopts_nr; i++)free (opts->xopts[i]);free (opts->xopts); -strbuf_addstr (&dir,get_dir (opts)); -remove_dir_recursively (&dir,0 ); -strbuf_release (&dir); +strbuf_reset (&buf); +strbuf_addstr (&buf,get_dir (opts)); +remove_dir_recursively (&buf,0 ); +strbuf_release (&buf);return 0 ; }@@ -1279,6 +1304,9 @@ enum todo_command {TODO_SQUASH ,/* commands that do something else than handling a single commit */ TODO_EXEC , +TODO_LABEL , +TODO_RESET , +TODO_MERGE ,/* commands that do nothing but are counted for reporting progress */ TODO_NOOP , TODO_DROP,@@ -1297,6 +1325,9 @@ static struct { { 'f', "fixup" }, { 's', "squash" }, { 'x', "exec" }, + { 'l', "label" }, + { 't', "reset" }, + { 'm', "merge" }, { 0, "noop" }, { 'd', "drop" }, { 0, NULL }@@ -1724,9 +1755,14 @@ static int read_and_refresh_cache(struct replay_opts *opts)return 0 ; } +enum todo_item_flags { +TODO_EDIT_MERGE_MSG =1 +}; +struct todo_item {enum todo_command command;struct commit *commit; +unsigned int flags;const char *arg;int arg_len;size_t offset_in_buf;@@ -1761,6 +1797,8 @@ static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)char *end_of_object_name;int i, saved, status, padding; + item->flags =0 ; +/* left-trim */ bol +=strspn (bol," \t" );@@ -1802,13 +1840,29 @@ static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)return error (_ ("missing arguments for %s" ),command_to_string (item->command)); -if (item->command ==TODO_EXEC ) { +if (item->command ==TODO_EXEC || item->command ==TODO_LABEL || + item->command ==TODO_RESET ) { item->commit =NULL ; item->arg = bol; item->arg_len = (int )(eol - bol);return 0 ; } +if (item->command ==TODO_MERGE ) { +if (skip_prefix (bol,"-C" , &bol)) + bol +=strspn (bol," \t" ); +else if (skip_prefix (bol,"-c" , &bol)) { + bol +=strspn (bol," \t" ); + item->flags |=TODO_EDIT_MERGE_MSG ; + }else { + item->flags |=TODO_EDIT_MERGE_MSG ; + item->commit =NULL ; + item->arg = bol; + item->arg_len = (int )(eol - bol); +return 0 ; + } + } + end_of_object_name = (char *) bol +strcspn (bol," \t\n" ); saved = *end_of_object_name; *end_of_object_name ='\0' ;@@ -2465,6 +2519,305 @@ static int do_exec(const char *command_line)return status; } +static int safe_append (const char *filename,const char *fmt, ...) +{ +va_list ap; +struct lock_file lock =LOCK_INIT ; +int fd =hold_lock_file_for_update (&lock, filename, +LOCK_REPORT_ON_ERROR ); +struct strbuf buf =STRBUF_INIT ; + +if (fd <0 ) +return -1 ; + +if (strbuf_read_file (&buf, filename,0 ) <0 && errno !=ENOENT ) { +error_errno (_ ("could not read '%s'" ), filename); +rollback_lock_file (&lock); +return -1 ; + } +strbuf_complete (&buf,'\n' ); +va_start (ap, fmt); +strbuf_vaddf (&buf, fmt, ap); +va_end (ap); + +if (write_in_full (fd, buf.buf, buf.len) <0 ) { +error_errno (_ ("could not write to '%s'" ), filename); +strbuf_release (&buf); +rollback_lock_file (&lock); +return -1 ; + } +if (commit_lock_file (&lock) <0 ) { +strbuf_release (&buf); +rollback_lock_file (&lock); +return error (_ ("failed to finalize '%s'" ), filename); + } + +strbuf_release (&buf); +return 0 ; +} + +static int do_label (const char *name,int len) +{ +struct ref_store *refs =get_main_ref_store (); +struct ref_transaction *transaction; +struct strbuf ref_name =STRBUF_INIT , err =STRBUF_INIT ; +struct strbuf msg =STRBUF_INIT ; +int ret =0 ; +struct object_id head_oid; + +if (len ==1 && *name =='#' ) +return error ("Illegal label name: '%.*s'" , len, name); + +strbuf_addf (&ref_name,"refs/rewritten/%.*s" , len, name); +strbuf_addf (&msg,"rebase -i (label) '%.*s'" , len, name); + + transaction =ref_store_transaction_begin (refs, &err); +if (!transaction) { +error ("%s" , err.buf); + ret =-1 ; + }else if (get_oid ("HEAD" , &head_oid)) { +error (_ ("could not read HEAD" )); + ret =-1 ; + }else if (ref_transaction_update (transaction, ref_name.buf, &head_oid, +NULL ,0 , msg.buf, &err) <0 || +ref_transaction_commit (transaction, &err)) { +error ("%s" , err.buf); + ret =-1 ; + } +ref_transaction_free (transaction); +strbuf_release (&err); +strbuf_release (&msg); + +if (!ret) + ret =safe_append (rebase_path_refs_to_delete (), +"%s\n" , ref_name.buf); +strbuf_release (&ref_name); + +return ret; +} + +static const char *reflog_message (struct replay_opts *opts, +const char *sub_action,const char *fmt, ...); + +static int do_reset (const char *name,int len,struct replay_opts *opts) +{ +struct strbuf ref_name =STRBUF_INIT ; +struct object_id oid; +struct lock_file lock =LOCK_INIT ; +struct tree_desc desc; +struct tree *tree; +struct unpack_trees_options unpack_tree_opts; +int ret =0 , i; + +if (hold_locked_index (&lock,LOCK_REPORT_ON_ERROR ) <0 ) +return -1 ; + +/* Determine the length of the label */ +for (i =0 ; i < len; i++) +if (isspace (name[i])) + len = i; + +strbuf_addf (&ref_name,"refs/rewritten/%.*s" , len, name); +if (get_oid (ref_name.buf, &oid) && +get_oid (ref_name.buf +strlen ("refs/rewritten/" ), &oid)) { +error (_ ("could not read '%s'" ), ref_name.buf); +rollback_lock_file (&lock); +strbuf_release (&ref_name); +return -1 ; + } + +memset (&unpack_tree_opts,0 ,sizeof (unpack_tree_opts)); + unpack_tree_opts.head_idx =1 ; + unpack_tree_opts.src_index = &the_index; + unpack_tree_opts.dst_index = &the_index; + unpack_tree_opts.fn = oneway_merge; + unpack_tree_opts.merge =1 ; + unpack_tree_opts.update =1 ; + +if (read_cache_unmerged ()) { +rollback_lock_file (&lock); +strbuf_release (&ref_name); +return error_resolve_conflict (_ (action_name (opts))); + } + +if (!fill_tree_descriptor (&desc, &oid)) { +error (_ ("failed to find tree of %s" ),oid_to_hex (&oid)); +rollback_lock_file (&lock); +free ((void *)desc.buffer); +strbuf_release (&ref_name); +return -1 ; + } + +if (unpack_trees (1 , &desc, &unpack_tree_opts)) { +rollback_lock_file (&lock); +free ((void *)desc.buffer); +strbuf_release (&ref_name); +return -1 ; + } + + tree =parse_tree_indirect (&oid); +prime_cache_tree (&the_index, tree); + +if (write_locked_index (&the_index, &lock,COMMIT_LOCK ) <0 ) + ret =error (_ ("could not write index" )); +free ((void *)desc.buffer); + +if (!ret) + ret =update_ref (reflog_message (opts,"reset" ,"'%.*s'" , + len, name),"HEAD" , &oid, +NULL ,0 ,UPDATE_REFS_MSG_ON_ERR ); + +strbuf_release (&ref_name); +return ret; +} + +static int do_merge (struct commit *commit,const char *arg,int arg_len, +int flags,struct replay_opts *opts) +{ +int run_commit_flags = (flags &TODO_EDIT_MERGE_MSG ) ? +EDIT_MSG |VERIFY_MSG :0 ; +struct strbuf ref_name =STRBUF_INIT ; +struct commit *head_commit, *merge_commit, *i; +struct commit_list *bases, *j, *reversed =NULL ; +struct merge_options o; +int merge_arg_len, oneline_offset, ret; +static struct lock_file lock; +const char *p; + +if (hold_locked_index (&lock,LOCK_REPORT_ON_ERROR ) <0 ) { + ret =-1 ; + goto leave_merge; + } + + head_commit =lookup_commit_reference_by_name ("HEAD" ); +if (!head_commit) { + ret =error (_ ("cannot merge without a current revision" )); + goto leave_merge; + } + + oneline_offset = arg_len; + merge_arg_len =strcspn (arg," \t\n" ); + p = arg + merge_arg_len; + p +=strspn (p," \t\n" ); +if (*p =='#' && (!p[1 ] ||isspace (p[1 ]))) { + p +=1 +strspn (p +1 ," \t\n" ); + oneline_offset = p - arg; + }else if (p - arg < arg_len) +BUG ("octopus merges are not supported yet: '%s'" , p); + +strbuf_addf (&ref_name,"refs/rewritten/%.*s" , merge_arg_len, arg); + merge_commit =lookup_commit_reference_by_name (ref_name.buf); +if (!merge_commit) { +/* fall back to non-rewritten ref or commit */ +strbuf_splice (&ref_name,0 ,strlen ("refs/rewritten/" ),"" ,0 ); + merge_commit =lookup_commit_reference_by_name (ref_name.buf); + } + +if (!merge_commit) { + ret =error (_ ("could not resolve '%s'" ), ref_name.buf); + goto leave_merge; + } + +if (commit) { +const char *message =get_commit_buffer (commit,NULL ); +const char *body; +int len; + +if (!message) { + ret =error (_ ("could not get commit message of '%s'" ), +oid_to_hex (&commit->object.oid)); + goto leave_merge; + } +write_author_script (message); +find_commit_subject (message, &body); + len =strlen (body); + ret =write_message (body, len,git_path_merge_msg (),0 ); +unuse_commit_buffer (commit, message); +if (ret) { +error_errno (_ ("could not write '%s'" ), +git_path_merge_msg ()); + goto leave_merge; + } + }else { +struct strbuf buf =STRBUF_INIT ; +int len; + +strbuf_addf (&buf,"author %s" ,git_author_info (0 )); +write_author_script (buf.buf); +strbuf_reset (&buf); + +if (oneline_offset < arg_len) { + p = arg + oneline_offset; + len = arg_len - oneline_offset; + }else { +strbuf_addf (&buf,"Merge branch '%.*s'" , + merge_arg_len, arg); + p = buf.buf; + len = buf.len; + } + + ret =write_message (p, len,git_path_merge_msg (),0 ); +strbuf_release (&buf); +if (ret) { +error_errno (_ ("could not write '%s'" ), +git_path_merge_msg ()); + goto leave_merge; + } + } + +write_message (oid_to_hex (&merge_commit->object.oid),GIT_SHA1_HEXSZ , +git_path_merge_head (),0 ); +write_message ("no-ff" ,5 ,git_path_merge_mode (),0 ); + + bases =get_merge_bases (head_commit, merge_commit); +for (j = bases; j; j = j->next) +commit_list_insert (j->item, &reversed); +free_commit_list (bases); + +read_cache (); +init_merge_options (&o); + o.branch1 ="HEAD" ; + o.branch2 = ref_name.buf; + o.buffer_output =2 ; + + ret =merge_recursive (&o, head_commit, merge_commit, reversed, &i); +if (ret <=0 ) +fputs (o.obuf.buf, stdout); +strbuf_release (&o.obuf); +if (ret <0 ) { +error (_ ("could not even attempt to merge '%.*s'" ), + merge_arg_len, arg); + goto leave_merge; + } +/* +* The return value of merge_recursive() is 1 on clean, and 0 on +* unclean merge. +* +* Let's reverse that, so that do_merge() returns 0 upon success and +* 1 upon failed merge (keeping the return value -1 for the cases where +* we will want to reschedule the `merge` command). +*/ + ret = !ret; + +if (active_cache_changed && +write_locked_index (&the_index, &lock,COMMIT_LOCK )) { + ret =error (_ ("merge: Unable to write new index file" )); + goto leave_merge; + } + +rollback_lock_file (&lock); +if (ret) +rerere (opts->allow_rerere_auto); +else + ret =run_git_commit (git_path_merge_msg (), opts, + run_commit_flags); + +leave_merge: +strbuf_release (&ref_name); +rollback_lock_file (&lock); +return ret; +} +static int is_final_fixup (struct todo_list *todo_list) {int i = todo_list->current;@@ -2568,7 +2921,7 @@ N_("Could not execute the todo command\n"static int pick_commits (struct todo_list *todo_list,struct replay_opts *opts) { -int res =0 ; +int res =0 , reschedule =0 ;setenv (GIT_REFLOG_ACTION ,action_name (opts),0 );if (opts->allow_ff)@@ -2639,7 +2992,7 @@ static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)intend_to_amend ();return error_failed_squash (item->commit, opts, item->arg_len, item->arg); - }else if (res &&is_rebase_i (opts)) + }else if (res &&is_rebase_i (opts) && item->commit)return res |error_with_patch (item->commit, item->arg, item->arg_len, opts, res, item->command ==TODO_REWORD );@@ -2665,9 +3018,41 @@ static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)/* `current` will be incremented below */ todo_list->current =-1 ; } + }else if (item->command ==TODO_LABEL ) { +if ((res =do_label (item->arg, item->arg_len))) + reschedule =1 ; + }else if (item->command ==TODO_RESET ) { +if ((res =do_reset (item->arg, item->arg_len, opts))) + reschedule =1 ; + }else if (item->command ==TODO_MERGE ) { +if ((res =do_merge (item->commit, + item->arg, item->arg_len, + item->flags, opts)) <0 ) + reschedule =1 ; +else if (res >0 ) +/* failed with merge conflicts */ +return error_with_patch (item->commit, + item->arg, + item->arg_len, opts, + res,0 ); }else if (!is_noop (item->command))return error (_ ("unknown command %d" ), item->command); +if (reschedule) { +advise (_ (rescheduled_advice), +get_item_line_length (todo_list, + todo_list->current), +get_item_line (todo_list, todo_list->current)); + todo_list->current--; +if (save_todo (todo_list, opts)) +return -1 ; +if (item->commit) +return error_with_patch (item->commit, + item->arg, + item->arg_len, opts, + res,0 ); + } + todo_list->current++;if (res)return res;@@ -3147,8 +3532,16 @@ int transform_todos(unsigned flags) short_commit_name(item->commit) :oid_to_hex (&item->commit->object.oid); +if (item->command ==TODO_MERGE ) { +if (item->flags &TODO_EDIT_MERGE_MSG ) +strbuf_addstr (&buf," -c" ); +else +strbuf_addstr (&buf," -C" ); + } +strbuf_addf (&buf," %s" , oid); } +/* add all the rest */ if (!item->arg_len)strbuf_addch (&buf,'\n' );
Re: [PATCH v8 06/16] sequencer: introduce the `merge` command
Quoted 17 lines · Phillip Wood
Quoted 8 lines · Johannes Schindelin
This patch is part of the effort to reimplement
--preserve-mergeswith a substantially improved design, a design that has been developed in the Git for Windows project to maintain the dozens of Windows-specific patch series on top of upstream Git.The previous patch implemented the
labelandresetcommands to label commits and to reset to labeled commits. This patch adds themergecommand, with the following syntax:The two patches seem to have been fused together in this series.
If the reset command fails because it would overwrite untracked files it says
error: Untracked working tree file 'b' would be overwritten by merge.
Quoted 8 lines
Followed by the hint to edit the todo file. Saying 'merge' rather 'reset' is possibly confusing to users. Perhaps it could call
setup_unpack_trees_porcelain(), though that would need to be extended to handle 'reset'.Also it currently refuses to overwrite ignored files which is either annoying or safe depending on one's point of view.
Looking at the existing code this is consistent with (most) of the rest of the sequencer. The code to fast-forward commits will overwrite ignored files, and I think the initial checkout will as well but the rest (picking commits and the new merge command) will not.
Quoted 592 lines
Best Wishes
Phillip
Quoted 587 lines
merge [-C <commit>] <rev> # <oneline>
The <commit> parameter in this instance is the *original* merge commit, whose author and message will be used for the merge commit that is about to be created.
The <rev> parameter refers to the (possibly rewritten) revision to merge. Let's see an example of a todo list:
label onto
# Branch abc
reset onto
pick deadbeef Hello, world!
label abcreset onto
pick cafecafe And now for something completely different merge -C baaabaaa abc # Merge the branch 'abc' into masterTo edit the merge commit's message (a "reword" for merges, if you will), use
-c(lower-case) instead of-C; this convention was borrowed fromgit committhat also supports-cand-Cwith similar meanings.To create *new* merges, i.e. without copying the commit message from an existing commit, simply omit the
-C <commit>parameter (which will open an editor for the merge message):merge abc
This comes in handy when splitting a branch into two or more branches.
Note: this patch only adds support for recursive merges, to keep things simple. Support for octopus merges will be added later in a separate patch series, support for merges using strategies other than the recursive merge is left for the future.
Signed-off-by Johannes Schindelin <[email protected]>---
git-rebase--interactive.sh| 6 +
sequencer.c | 407 ++++++++++++++++++++++++++++++++++++-2 files changed, 406 insertions(+), 7 deletions(-)git-rebase--interactive.sh +0
-0@@ -162,6 +162,12 @@ s, squash <commit> = use commit, but meld intoprevious commit
f, fixup <commit> = like \"squash\", but discard this commit's log message
x, exec <commit> = run command (the rest of the line) using shell d, drop <commit> = remove commitgit-rebase--interactive.sh +6
-0+l, label <label> = label current HEAD with a name +t, reset <label> = reset HEAD to a label +m, merge [-C <commit> | -c <commit>] <label> [# <oneline>] +. create a merge commit using the original merge commit's +. message (or the oneline, if no original merge commit was +. specified). Use -c <commit> to reword the commit message.These lines can be re-ordered; they are executed from top to bottom. " | git stripspace --comment-lines >>"$todo"
sequencer.c +2
-0@@ -23,6 +23,8 @@ #include "hashmap.h" #include "notes-utils.h" #include "sigchain.h" +#include "unpack-trees.h" +#include "worktree.h" #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION" @@ -120,6 +122,13 @@ static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")static
GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
staticGIT_PATH_FUNC(rebase_path_rewritten_pending, "rebase-merge/rewritten-pending")sequencer.c +3
-0+ +/* +* The path of the file listing refs that need to be deleted after the rebase
+ * finishes. This is used by thelabelcommand to record the need for cleanup.
+ */
+staticGIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
+
/*
* The following files are written by git-rebase just after parsing the
* command-line (and are only consumed, not modified, by the sequencer).sequencer.c +1
-1@@ -244,18 +253,34 @@ static const char *gpg_sign_opt_quoted(struct replay_opts *opts) int sequencer_remove_state(struct replay_opts *opts) { - struct strbuf dir = STRBUF_INIT; + struct strbuf buf = STRBUF_INIT; int i;+ if (
is_rebase_i(opts)&&
+strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0)> 0) { + char *p = buf.buf;
+ while (*p) {
+ char *eol =strchr(p, '\n');
+ if (eol)
+ *eol = '\0';
+ if (delete_ref("(rebase -i) cleanup", p, NULL, 0)< 0) +warning(_("could not delete '%s'"), p);
+ if (!eol)
+ break;
+ p = eol + 1;
+ }
+ }
+
free(opts->gpg_sign);
free(opts->strategy);
for (i = 0; i <opts->xopts_nr; i++)free(opts->xopts[i]);
free(opts->xopts);
-strbuf_addstr(&dir, get_dir(opts));
-remove_dir_recursively(&dir, 0);
-strbuf_release(&dir);
+strbuf_reset(&buf);
+strbuf_addstr(&buf, get_dir(opts));
+remove_dir_recursively(&buf, 0);
+strbuf_release(&buf);
return 0;
}sequencer.c +3
-0@@ -1279,6 +1304,9 @@ enum todo_command { TODO_SQUASH, /* commands that do something else than handling a single commit */ TODO_EXEC, + TODO_LABEL, + TODO_RESET, + TODO_MERGE, /* commands that do nothing but are counted for reportingprogress */
TODO_NOOP,
TODO_DROP,sequencer.c +7
-0@@ -1297,6 +1325,9 @@ static struct { { 'f', "fixup" }, { 's', "squash" }, { 'x', "exec" }, + { 'l', "label" }, + { 't', "reset" }, + { 'm', "merge" }, { 0, "noop" }, { 'd', "drop" }, { 0, NULL }@@ -1724,9 +1755,14 @@ static int read_and_refresh_cache(struct replay_opts *opts) return 0; } +enum todo_item_flags { + TODO_EDIT_MERGE_MSG = 1 +}; + struct todo_item { enum todo_command command; struct commit *commit; + unsigned int flags; const char *arg; int arg_len;
size_toffset_in_buf;sequencer.c +1
-0@@ -1761,6 +1797,8 @@ static int parse_insn_line(struct todo_item *item, const char *bol, char *eol) char *end_of_object_name; int i, saved, status, padding; + item->flags = 0; + /* left-trim */ bol += strspn(bol, " \t");@@ -1802,13 +1840,29 @@ static int
parse_insn_line(struct todo_item *item, const char *bol, char *eol)
returnerror(_("missing arguments for %s"), command_to_string(item->command));
- if (item->command==TODO_EXEC) {
+ if (item->command==TODO_EXEC||item->command==TODO_LABEL|| +item->command==TODO_RESET) {
item->commit= NULL;
item->arg= bol;
item->arg_len= (int)(eol - bol);
return 0;
}
+ if (item->command==TODO_MERGE) {
+ if (skip_prefix(bol, "-C", &bol))
+ bol +=strspn(bol, " \t");
+ else if (skip_prefix(bol, "-c", &bol)) {
+ bol +=strspn(bol, " \t");
+item->flags|=TODO_EDIT_MERGE_MSG;
+ } else {
+item->flags|=TODO_EDIT_MERGE_MSG;
+item->commit= NULL;
+item->arg= bol;
+item->arg_len= (int)(eol - bol);
+ return 0;
+ }
+ }
+
end_of_object_name= (char *) bol +strcspn(bol, " \t\n"); saved =*end_of_object_name;
*end_of_object_name= '\0';sequencer.c +275
-0@@ -2465,6 +2519,305 @@ static int do_exec(const char *command_line) return status; } +static int safe_append(const char *filename, const char *fmt, ...) +{ + va_list ap; + struct lock_file lock = LOCK_INIT; + int fd = hold_lock_file_for_update(&lock, filename, + LOCK_REPORT_ON_ERROR); + struct strbuf buf = STRBUF_INIT; + + if (fd < 0) + return -1; + + if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) { + error_errno(_("could not read '%s'"), filename); + rollback_lock_file(&lock); + return -1; + } + strbuf_complete(&buf, '\n'); + va_start(ap, fmt); + strbuf_vaddf(&buf, fmt, ap); + va_end(ap); + + if (write_in_full(fd, buf.buf, buf.len) < 0) { + error_errno(_("could not write to '%s'"), filename); + strbuf_release(&buf); + rollback_lock_file(&lock); + return -1; + } + if (commit_lock_file(&lock) < 0) { + strbuf_release(&buf); + rollback_lock_file(&lock); + return error(_("failed to finalize '%s'"), filename); + } + + strbuf_release(&buf); + return 0; +} + +static int do_label (const char *name,int len) +{ + struct ref_store *refs = get_main_ref_store(); + struct ref_transaction *transaction; + struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT; + struct strbuf msg = STRBUF_INIT; + int ret = 0; + struct object_id head_oid; + + if (len == 1 && *name == '#') + return error("Illegal label name: '%.*s'", len, name); + + strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name); + strbuf_addf(&msg, "rebase -i (label) '%.*s'", len, name); + + transaction = ref_store_transaction_begin(refs, &err); + if (!transaction) { + error("%s", err.buf); + ret = -1; + } else if (get_oid("HEAD", &head_oid)) { + error(_("could not read HEAD")); + ret = -1; + } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid, + NULL, 0, msg.buf, &err) < 0 || + ref_transaction_commit(transaction, &err)) { + error("%s", err.buf); + ret = -1; + } + ref_transaction_free(transaction); + strbuf_release(&err); + strbuf_release(&msg); + + if (!ret) + ret = safe_append(rebase_path_refs_to_delete(), + "%s\n", ref_name.buf); + strbuf_release(&ref_name); + + return ret; +} + +static const char *reflog_message (struct replay_opts *opts, + const char *sub_action, const char *fmt, ...); + +static int do_reset (const char *name,int len,struct replay_opts *opts) +{ + struct strbuf ref_name = STRBUF_INIT; + struct object_id oid; + struct lock_file lock = LOCK_INIT; + struct tree_desc desc; + struct tree *tree; + struct unpack_trees_options unpack_tree_opts; + int ret = 0, i; + + if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0) + return -1; + + /* Determine the length of the label */ + for (i = 0; i < len; i++) + if (isspace(name[i])) + len = i; + + strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name); + if (get_oid(ref_name.buf, &oid) && + get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) { + error(_("could not read '%s'"), ref_name.buf); + rollback_lock_file(&lock); + strbuf_release(&ref_name); + return -1; + } + + memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts)); + unpack_tree_opts.head_idx = 1; + unpack_tree_opts.src_index = &the_index; + unpack_tree_opts.dst_index = &the_index; + unpack_tree_opts.fn = oneway_merge; + unpack_tree_opts.merge = 1; + unpack_tree_opts.update = 1; + + if (read_cache_unmerged()) { + rollback_lock_file(&lock); + strbuf_release(&ref_name); + return error_resolve_conflict(_(action_name(opts))); + } + + if (!fill_tree_descriptor(&desc, &oid)) { + error(_("failed to find tree of %s"), oid_to_hex(&oid)); + rollback_lock_file(&lock); + free((void *)desc.buffer); + strbuf_release(&ref_name); + return -1; + } + + if (unpack_trees(1, &desc, &unpack_tree_opts)) { + rollback_lock_file(&lock); + free((void *)desc.buffer); + strbuf_release(&ref_name); + return -1; + } + + tree = parse_tree_indirect(&oid); + prime_cache_tree(&the_index, tree); + + if (write_locked_index(&the_index, &lock, COMMIT_LOCK) < 0) + ret = error(_("could not write index")); + free((void *)desc.buffer); + + if (!ret) + ret = update_ref(reflog_message(opts, "reset", "'%.*s'", + len, name), "HEAD", &oid, + NULL, 0, UPDATE_REFS_MSG_ON_ERR); + + strbuf_release(&ref_name); + return ret; +} + +static int do_merge (struct commit *commit,const char *arg,int arg_len, + int flags, struct replay_opts *opts) +{ + int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ? + EDIT_MSG | VERIFY_MSG : 0; + struct strbuf ref_name = STRBUF_INIT; + struct commit *head_commit, *merge_commit, *i; + struct commit_list *bases, *j, *reversed = NULL; + struct merge_options o; + int merge_arg_len, oneline_offset, ret; + static struct lock_file lock; + const char *p; + + if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0) { + ret = -1; + goto leave_merge; + } + + head_commit = lookup_commit_reference_by_name("HEAD"); + if (!head_commit) { + ret = error(_("cannot merge without a current revision")); + goto leave_merge; + } + + oneline_offset = arg_len; + merge_arg_len = strcspn(arg, " \t\n"); + p = arg + merge_arg_len; + p += strspn(p, " \t\n"); + if (*p == '#' && (!p[1] || isspace(p[1]))) { + p += 1 + strspn(p + 1, " \t\n"); + oneline_offset = p - arg; + } else if (p - arg < arg_len) + BUG("octopus merges are not supported yet: '%s'", p); + + strbuf_addf(&ref_name, "refs/rewritten/%.*s", merge_arg_len, arg); + merge_commit = lookup_commit_reference_by_name(ref_name.buf); + if (!merge_commit) { + /* fall back to non-rewritten ref or commit */ + strbuf_splice(&ref_name, 0, strlen("refs/rewritten/"), "", 0); + merge_commit = lookup_commit_reference_by_name(ref_name.buf); + } + + if (!merge_commit) { + ret = error(_("could not resolve '%s'"), ref_name.buf); + goto leave_merge; + } + + if (commit) { + const char *message = get_commit_buffer(commit, NULL); + const char *body; + int len; + + if (!message) { + ret = error(_("could not get commit message of '%s'"), + oid_to_hex(&commit->object.oid)); + goto leave_merge; + } + write_author_script(message); + find_commit_subject(message, &body); + len = strlen(body); + ret = write_message(body, len, git_path_merge_msg(), 0); + unuse_commit_buffer(commit, message); + if (ret) { + error_errno(_("could not write '%s'"), + git_path_merge_msg()); + goto leave_merge; + } + } else { + struct strbuf buf = STRBUF_INIT; + int len; + + strbuf_addf(&buf, "author %s", git_author_info(0)); + write_author_script(buf.buf); + strbuf_reset(&buf); + + if (oneline_offset < arg_len) { + p = arg + oneline_offset; + len = arg_len - oneline_offset; + } else { + strbuf_addf(&buf, "Merge branch '%.*s'", + merge_arg_len, arg); + p = buf.buf; + len = buf.len; + } + + ret = write_message(p, len, git_path_merge_msg(), 0); + strbuf_release(&buf); + if (ret) { + error_errno(_("could not write '%s'"), + git_path_merge_msg()); + goto leave_merge; + } + } + + write_message(oid_to_hex(&merge_commit->object.oid), GIT_SHA1_HEXSZ, + git_path_merge_head(), 0); + write_message("no-ff", 5, git_path_merge_mode(), 0); + + bases = get_merge_bases(head_commit, merge_commit); + for (j = bases; j; j = j->next) + commit_list_insert(j->item, &reversed); + free_commit_list(bases); + + read_cache(); + init_merge_options(&o); + o.branch1 = "HEAD"; + o.branch2 = ref_name.buf; + o.buffer_output = 2; + + ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i); + if (ret <= 0) + fputs(o.obuf.buf, stdout); + strbuf_release(&o.obuf); + if (ret < 0) { + error(_("could not even attempt to merge '%.*s'"), + merge_arg_len, arg); + goto leave_merge; + } + /* +* The return value of merge_recursive() is 1 on clean, and 0 on +* unclean merge. +* +* Let's reverse that, so that do_merge() returns 0 upon success and +* 1 upon failed merge (keeping the return value -1 for the cases where
+ * we will want to reschedule themergecommand). + */
+ ret = !ret;sequencer.c +20
-0+ + if (active_cache_changed && + write_locked_index(&the_index, &lock, COMMIT_LOCK)) { + ret = error(_("merge: Unable to write new index file")); + goto leave_merge; + } + + rollback_lock_file(&lock); + if (ret) + rerere(opts->allow_rerere_auto); + else + ret = run_git_commit(git_path_merge_msg(), opts, + run_commit_flags); + +leave_merge: + strbuf_release(&ref_name); + rollback_lock_file(&lock); + return ret; +} +static int
is_final_fixup(struct todo_list *todo_list){
int i =todo_list->current;sequencer.c +0
-0@@ -2568,7 +2921,7 @@ N_("Could not execute the todo command\n"static int
pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
{
- int res = 0;
+ int res = 0, reschedule = 0;setenv(GIT_REFLOG_ACTION, action_name(opts), 0); if (opts->allow_ff)sequencer.c +1
-1@@ -2639,7 +2992,7 @@ static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts) intend_to_amend(); return error_failed_squash(item->commit, opts, item->arg_len, item->arg); - } else if (res && is_rebase_i(opts)) + } else if (res && is_rebase_i(opts) && item->commit) return res | error_with_patch(item->commit, item->arg, item->arg_len, opts, res,
item->command==TODO_REWORD);sequencer.c +31
-0@@ -2665,9 +3018,41 @@ static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts) /* `current` will be incremented below */ todo_list->current = -1; } + } else if (item->command == TODO_LABEL) { + if ((res = do_label(item->arg, item->arg_len))) + reschedule = 1; + } else if (item->command == TODO_RESET) { + if ((res = do_reset(item->arg, item->arg_len, opts))) + reschedule = 1; + } else if (item->command == TODO_MERGE) { + if ((res = do_merge(item->commit, + item->arg, item->arg_len, + item->flags, opts)) < 0) + reschedule = 1; + else if (res > 0) + /* failed with merge conflicts */ + return error_with_patch(item->commit, + item->arg, + item->arg_len, opts, + res, 0); } else if (!is_noop(item->command)) return error(_("unknown command %d"), item->command); + if (reschedule) { + advise(_(rescheduled_advice), + get_item_line_length(todo_list, + todo_list->current), + get_item_line(todo_list, todo_list->current)); + todo_list->current--; + if (save_todo(todo_list, opts)) + return -1; + if (item->commit) + return error_with_patch(item->commit, + item->arg, + item->arg_len, opts, + res, 0); + } + todo_list->current++; if (res)return res;
sequencer.c +0
-0@@ -3147,8 +3532,16 @@ int transform_todos(unsigned flags)
short_commit_name(item->commit):
oid_to_hex(&item->commit->object.oid); + if (item->command==TODO_MERGE) {
+ if (item->flags&TODO_EDIT_MERGE_MSG) +strbuf_addstr(&buf, " -c");
+ else
+strbuf_addstr(&buf, " -C");
+ }
+
strbuf_addf(&buf, " %s", oid);
}
+
/* add all the rest */
if (!item->arg_len)
strbuf_addch(&buf, '\n');
Re: [PATCH v8 06/16] sequencer: introduce the `merge` command
Hi Phillip,
Quoted 24 lines · Phillip Wood
Quoted 21 lines · Phillip Wood
Quoted 8 lines · Johannes Schindelin
This patch is part of the effort to reimplement
--preserve-mergeswith a substantially improved design, a design that has been developed in the Git for Windows project to maintain the dozens of Windows-specific patch series on top of upstream Git.The previous patch implemented the
labelandresetcommands to label commits and to reset to labeled commits. This patch adds themergecommand, with the following syntax:The two patches seem to have been fused together in this series.
If the reset command fails because it would overwrite untracked files it says
error: Untracked working tree file 'b' would be overwritten by merge.
Followed by the hint to edit the todo file. Saying 'merge' rather 'reset' is possibly confusing to users. Perhaps it could call
setup_unpack_trees_porcelain(), though that would need to be extended to handle 'reset'.
Quoted 7 lines
Quoted 2 lines
Also it currently refuses to overwrite ignored files which is either annoying or safe depending on one's point of view.
Looking at the existing code this is consistent with (most) of the rest of the sequencer. The code to fast-forward commits will overwrite ignored files, and I think the initial checkout will as well but the rest (picking commits and the new merge command) will not.
I never thought about that... but then, I never came close to encountering such an issue, as I do not typically turn ignored files into tracked ones ;-)
Ciao,
Dscho
Re: [PATCH v8 06/16] sequencer: introduce the `merge` command
In reply to Phillip WoodHi Phillip,
Quoted 11 lines · Phillip Wood
Quoted 8 lines · Johannes Schindelin
This patch is part of the effort to reimplement
--preserve-mergeswith a substantially improved design, a design that has been developed in the Git for Windows project to maintain the dozens of Windows-specific patch series on top of upstream Git.The previous patch implemented the
labelandresetcommands to label commits and to reset to labeled commits. This patch adds themergecommand, with the following syntax:The two patches seem to have been fused together in this series.
Indeed. I have yet to investigate further how that happened, it could be a bug in my series after all.
Quoted 9 lines
If the reset command fails because it would overwrite untracked files it says
error: Untracked working tree file 'b' would be overwritten by merge.
Followed by the hint to edit the todo file. Saying 'merge' rather 'reset' is possibly confusing to users. Perhaps it could call
setup_unpack_trees_porcelain(), though that would need to be extended to handle 'reset'.
Yes, and it changes global state :-(
Maybe we can leave it as-is for now? After all, it should be clear to the user what is happening. The most important part is the "Untracked working tree file"...
Quoted 2 lines
Also it currently refuses to overwrite ignored files which is either annoying or safe depending on one's point of view.
Let me think about that. My gut feeling says: if it is easy to do, then let's nuke ignored files, but keep untracked files. But I do not think that the unpack-trees machinery was taught to know about .gitignore...
Seeing as label and reset really are mostly about revisions we see along the lines, I think that the common case will *not* overwrite any untracked files, ever. You would have to use reset on a not-previously-seen commit and/or add exec commands designed to interfere with the reset.
So I tend to want to not bother with discerning between untracked and ignored files here.
Ciao,
Dscho
Re: [PATCH v8 06/16] sequencer: introduce the `merge` command
Quoted 29 lines · Johannes Schindelin
Hi Phillip,
Quoted 11 lines · Phillip Wood
Quoted 8 lines · Johannes Schindelin
This patch is part of the effort to reimplement
--preserve-mergeswith a substantially improved design, a design that has been developed in the Git for Windows project to maintain the dozens of Windows-specific patch series on top of upstream Git.The previous patch implemented the
labelandresetcommands to label commits and to reset to labeled commits. This patch adds themergecommand, with the following syntax:The two patches seem to have been fused together in this series.
Indeed. I have yet to investigate further how that happened, it could be a bug in my series after all.
Quoted 9 lines
If the reset command fails because it would overwrite untracked files it says
error: Untracked working tree file 'b' would be overwritten by merge.
Followed by the hint to edit the todo file. Saying 'merge' rather 'reset' is possibly confusing to users. Perhaps it could call
setup_unpack_trees_porcelain(), though that would need to be extended to handle 'reset'.
Quoted 5 lines
Yes, and it changes global state :-(
Maybe we can leave it as-is for now? After all, it should be clear to the user what is happening. The most important part is the "Untracked working tree file"...
I'm fine with leaving it, I've might get round to doing a small series to clean things up slightly in a few weeks. At the moment setup_unpack_trees_porcelain() leaks memory as it is called for each merge and allocates new strings each time. It would also be nice if the error messages reflected the command, so it said 'cherry-pick', 'revert' or 'reset' rather than 'merge'
Quoted 7 lines
Quoted 2 lines
Also it currently refuses to overwrite ignored files which is either annoying or safe depending on one's point of view.
Let me think about that. My gut feeling says: if it is easy to do, then let's nuke ignored files, but keep untracked files. But I do not think that the unpack-trees machinery was taught to know about .gitignore...
Quoted 8 lines
Seeing as
labelandresetreally are mostly about revisions we see along the lines, I think that the common case will *not* overwrite any untracked files, ever. You would have to usereseton a not-previously-seen commit and/or addexeccommands designed to interfere with thereset.So I tend to want to not bother with discerning between untracked and ignored files here.
I don't think it's a pressing concern. In the past I once had a patch series that removed some tracked files in favor of having the build system generate them and added them to .gitignore. Each time I rebased I had to manually remove them at some stage which was annoying but that is quite a rare occurrence.
Best Wishes
Phillip
Quoted 3 lines
Ciao,
Dscho
Re: [PATCH v8 06/16] sequencer: introduce the `merge` command
Hi Phillip,
Quoted 6 lines · Phillip Wood
I'm fine with leaving it, I've might get round to doing a small series to clean things up slightly in a few weeks. At the moment
setup_unpack_trees_porcelain()leaks memory as it is called for each merge and allocates new strings each time. It would also be nice if the error messages reflected the command, so it said 'cherry-pick', 'revert' or 'reset' rather than 'merge'
This is a small patch series to introduce and use clear_unpack_trees_porcelain(). Since Elijah is doing substantial rewrites to one of the users of setup_unpack_trees_porcelain() [1], I think we should hold off on these for now to avoid a quite evil merge. (I haven't studied the details enough to be confident, but I think the calls to setup_...() and clear_...() might need to be moved up the call-chain.)
I'm posting this so we don't repeat each other's work. If you feel like picking these up and running with them, go ahead. Otherwise, I will try to get them in as soon as Elijah's series lands. I'll keep you posted.
[1] https://public-inbox.org/git/CAN0heSquJboMMgay+5XomqXCGoHtXxf1mJBmY_L7y+AA4eG0KA@mail.gmail.com/#t
Martin
Martin Ågren (2):
merge: setup opts later in checkout_fast_forward()
unpack_trees_options: free messages when done
unpack-trees.h | 5 +++++ builtin/checkout.c | 1 + merge-recursive.c | 1 + merge.c | 35 ++++++++++++++++++++--------------- unpack-trees.c | 11 +++++++++++ 5 files changed, 38 insertions(+), 15 deletions(-)
Signature · 1 line
2.17.0
PATCH 1/2 merge: setup `opts` later in `checkout_fast_forward()`
After we initialize the various fields in opts but before we actually use them, we might return early. Move the initialization further down, to immediately before we use opts.
This limits the scope of opts and will help a subsequent commit fix a memory leak without having to worry about those early returns.
--- merge.c | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-)
merge.c +17 -15
@@ -94,8 +94,24 @@ int checkout_fast_forward(const struct object_id *head,return -1 ;memset (&trees,0 ,sizeof (trees)); -memset (&opts,0 ,sizeof (opts));memset (&t,0 ,sizeof (t)); + + trees[nr_trees] =parse_tree_indirect (head); +if (!trees[nr_trees++]) { +rollback_lock_file (&lock_file); +return -1 ; + } + trees[nr_trees] =parse_tree_indirect (remote); +if (!trees[nr_trees++]) { +rollback_lock_file (&lock_file); +return -1 ; + } +for (i =0 ; i < nr_trees; i++) { +parse_tree (trees[i]); +init_tree_desc (t+i, trees[i]->buffer, trees[i]->size); + } + +memset (&opts,0 ,sizeof (opts));if (overwrite_ignore) {memset (&dir,0 ,sizeof (dir)); dir.flags |=DIR_SHOW_IGNORED ;
@@ -112,20 +128,6 @@ int checkout_fast_forward(const struct object_id *head, opts.fn = twoway_merge;setup_unpack_trees_porcelain (&opts,"merge" ); - trees[nr_trees] =parse_tree_indirect (head); -if (!trees[nr_trees++]) { -rollback_lock_file (&lock_file); -return -1 ; - } - trees[nr_trees] =parse_tree_indirect (remote); -if (!trees[nr_trees++]) { -rollback_lock_file (&lock_file); -return -1 ; - } -for (i =0 ; i < nr_trees; i++) { -parse_tree (trees[i]); -init_tree_desc (t+i, trees[i]->buffer, trees[i]->size); - }if (unpack_trees (nr_trees, t, &opts)) {rollback_lock_file (&lock_file);return -1 ;
Signature · 1 line
2.17.0
Re: [PATCH 1/2] merge: setup `opts` later in `checkout_fast_forward()`
Quoted 31 lines · Martin Ågren
After we initialize the various fields in
optsbut before we actually use them, we might return early. Move the initialization further down, to immediately before we useopts.This limits the scope of
optsand will help a subsequent commit fix a memory leak without having to worry about those early returns.Signed-off-by Martin Ågren <[email protected]>--- merge.c | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-)merge.c +9
-1@@ -94,8 +94,24 @@ int checkout_fast_forward(const struct object_id *head,return -1 ;memset (&trees,0 ,sizeof (trees)); -memset (&opts,0 ,sizeof (opts));memset (&t,0 ,sizeof (t)); + + trees[nr_trees] =parse_tree_indirect (head); +if (!trees[nr_trees++]) { +rollback_lock_file (&lock_file); +return -1 ; + } + trees[nr_trees] =parse_tree_indirect (remote); +if (!trees[nr_trees++]) { +rollback_lock_file (&lock_file);
merge.c int checkout_fast_forward(const struct object_id *head, · line 116
Quoted 10 lines
merge.c +8
-0+return -1 ; + } +for (i =0 ; i < nr_trees; i++) { +parse_tree (trees[i]); +init_tree_desc (t+i, trees[i]->buffer, trees[i]->size); + } + +memset (&opts,0 ,sizeof (opts));if (overwrite_ignore) {memset (&dir,0 ,sizeof (dir));
I'm guessing the diff algorithm simply found that this was a more compact representation of the change? It's a bit confusing when your description indicates you "moved" some code down, but it looks like you moved code up.
Thanks,
Jake
Quoted 25 lines
merge.c +0
-15dir.flags |=DIR_SHOW_IGNORED ;@@ -112,20 +128,6 @@ int checkout_fast_forward(const struct object_id *head, opts.fn = twoway_merge;setup_unpack_trees_porcelain (&opts,"merge" ); - trees[nr_trees] =parse_tree_indirect (head); -if (!trees[nr_trees++]) { -rollback_lock_file (&lock_file); -return -1 ; - } - trees[nr_trees] =parse_tree_indirect (remote); -if (!trees[nr_trees++]) { -rollback_lock_file (&lock_file); -return -1 ; - } -for (i =0 ; i < nr_trees; i++) { -parse_tree (trees[i]); -init_tree_desc (t+i, trees[i]->buffer, trees[i]->size); - }if (unpack_trees (nr_trees, t, &opts)) {rollback_lock_file (&lock_file);return -1 ; --2.17.0
Re: [PATCH 1/2] merge: setup `opts` later in `checkout_fast_forward()`
Quoted 4 lines · Jacob Keller
I'm guessing the diff algorithm simply found that this was a more compact representation of the change? It's a bit confusing when your description indicates you "moved" some code down, but it looks like you moved code up.
Agreed. I'll play with --anchored and other magic stuff to see if I can improve this. Or I could instead try to sell this patch as "move some other stuff out of the way" ;-) That seems a bit less direct though.
Thanks
Martin
Re: [PATCH 1/2] merge: setup `opts` later in `checkout_fast_forward()`
Hi Martin,
Quoted 9 lines · Martin Ågren
Quoted 4 lines · Jacob Keller
I'm guessing the diff algorithm simply found that this was a more compact representation of the change? It's a bit confusing when your description indicates you "moved" some code down, but it looks like you moved code up.
Agreed. I'll play with --anchored and other magic stuff to see if I can improve this. Or I could instead try to sell this patch as "move some other stuff out of the way" ;-) That seems a bit less direct though.
Or you could add a remark to the commit message along the lines "best viewed with --anchored=...". This is what I would do ;-)
Ciao,
Dscho
PATCH 2/2 unpack_trees_options: free messages when done
In reply to Martin ÅgrenThe strings allocated in setup_unpack_trees_porcelain() are never freed. Provide a function clear_unpack_trees_porcelain() to do so and call it in the functions which use setup_unpack_trees_porcelain().
In all current callers, the pointers are about to go out of scope, so we do not need to set them to NULL. Let's do so anyway so that a future caller or restructured code doesn't suddenly start accessing dangling pointers.
Note that we only take responsibility for the memory allocated in setup_unpack_trees_porcelain() and not any other members of the struct unpack_trees_options.
--- unpack-trees.h | 5 +++++ builtin/checkout.c | 1 + merge-recursive.c | 1 + merge.c | 3 +++ unpack-trees.c | 11 +++++++++++ 5 files changed, 21 insertions(+)
unpack-trees.h +5 -0
@@ -32,6 +32,11 @@ enum unpack_trees_error_types {void setup_unpack_trees_porcelain (struct unpack_trees_options *opts,const char *cmd); +/* +* Frees resources allocated by setup_unpack_trees_porcelain(). +*/ +extern void clear_unpack_trees_porcelain (struct unpack_trees_options *opts); +struct unpack_trees_options {unsigned int reset, merge,
builtin/checkout.c +1 -0
@@ -526,6 +526,7 @@ static int merge_working_tree(const struct checkout_opts *opts,init_tree_desc (&trees[1 ], tree->buffer, tree->size); ret =unpack_trees (2 , trees, &topts); +clear_unpack_trees_porcelain (&topts);if (ret ==-1 ) {/* * Unpack couldn't do a trivial merge; either
merge-recursive.c +1 -0
@@ -301,6 +301,7 @@ static int git_merge_trees(int index_only,init_tree_desc_from_tree (t+2 , merge); rc =unpack_trees (3 , t, &opts); +clear_unpack_trees_porcelain (&opts);cache_tree_free (&active_cache_tree);return rc; }
merge.c +3 -0
@@ -130,8 +130,11 @@ int checkout_fast_forward(const struct object_id *head,if (unpack_trees (nr_trees, t, &opts)) {rollback_lock_file (&lock_file); +clear_unpack_trees_porcelain (&opts);return -1 ; } +clear_unpack_trees_porcelain (&opts); +if (write_locked_index (&the_index, &lock_file,COMMIT_LOCK ))return error (_ ("unable to write new index file" ));return 0 ;
unpack-trees.c +11 -0
@@ -179,6 +179,17 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts, opts->unpack_rejects[i].strdup_strings =1 ; } +void clear_unpack_trees_porcelain (struct unpack_trees_options *opts) +{ +char **msgs = (char **)opts->msgs; + +free (msgs[ERROR_WOULD_OVERWRITE ]); +free (msgs[ERROR_WOULD_LOSE_UNTRACKED_REMOVED ]); +free (msgs[ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN ]); + +memset (opts->msgs,0 ,sizeof (opts->msgs)); +} +static int do_add_entry (struct unpack_trees_options *o,struct cache_entry *ce,unsigned int set,unsigned int clear) {
Signature · 1 line
2.17.0
Re: [PATCH 2/2] unpack_trees_options: free messages when done
Quoted 3 lines · Martin Ågren
The strings allocated in
setup_unpack_trees_porcelain()are never freed. Provide a functionclear_unpack_trees_porcelain()to do so and call it in the functions which usesetup_unpack_trees_porcelain().
This is awesome; thanks.
merge-recursive.c static int git_merge_trees(int index_only, · line 306
Quoted 11 lines
merge-recursive.c +1
-0@@ -301,6 +301,7 @@ static int git_merge_trees(int index_only,init_tree_desc_from_tree (t+2 , merge); rc =unpack_trees (3 , t, &opts); +clear_unpack_trees_porcelain (&opts);cache_tree_free (&active_cache_tree);return rc;
Yeah, this could result in an evil merge. In my series, I want to continue to be able to call verify_uptodate() from unpack_trees.c in order to check if files affected by renames are dirty and we need to avoid overwriting them. That can trigger error messages, so they need to not be freed until later. So, instead, I'd like to see something like the below (built on top of my series):
-- >8 --
--- merge-recursive.c | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-)
merge-recursive.c +12 -13
@@ -337,10 +337,10 @@ static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree)init_tree_desc (desc, tree->buffer, tree->size); } -static int git_merge_trees (struct merge_options *o, -struct tree *common, -struct tree *head, -struct tree *merge) +static int unpack_trees_start (struct merge_options *o, +struct tree *common, +struct tree *head, +struct tree *merge) {int rc;struct tree_desc t[3 ];
@@ -378,6 +378,12 @@ static int git_merge_trees(struct merge_options *o,return rc; } +static void unpack_trees_finish (struct merge_options *o) +{ +discard_index (&o->orig_index); +clear_unpack_trees_porcelain (&o->unpack_opts); +} +struct tree *write_tree_from_memory (struct merge_options *o) {struct tree *result =NULL ;
@@ -3079,7 +3085,7 @@ int merge_trees(struct merge_options *o,return 1 ; } - code =git_merge_trees (o, common, head, merge); + code =unpack_trees_start (o, common, head, merge);if (code !=0 ) {if (show (o,4 ) || o->call_depth)
@@ -3144,14 +3150,7 @@ int merge_trees(struct merge_options *o,else clean =1 ; -/* Free the extra index left from git_merge_trees() */ -/* -* FIXME: Need to also free data allocated by -* setup_unpack_trees_porcelain() tucked away in o->unpack_opts.msgs, -* but the problem is that only half of it refers to dynamically -* allocated data, while the other half points at static strings. -*/ -discard_index (&o->orig_index); +unpack_trees_finish (o);if (o->call_depth && !(*result =write_tree_from_memory (o)))return -1 ;
Signature · 1 line
2.17.0.295.g791b7256b2.dirty
Re: [PATCH 2/2] unpack_trees_options: free messages when done
From: Elijah Newren <[email protected]>
Hi Elijah,
[Since this is leaving the topic of rename-detection in favour of leak-plugging, I'm shortening the cc-list a bit.]
Quoted 2 lines
So, instead, I'd like to see something like the below (built on top of my series):
Thanks a lot. I now have the below patch in my tree as a preparatory part of a three-patch series on top of your series. Since the gist of this patch is entirely your creation, is it ok if I place your Author:
and Signed-off-by: on it? Credit where credit is due.
As you noted elsewhere [1], Ben is also working in this area. I'd be perfectly happy to sit on these patches until both of your contributions come through to master.
[1] https://public-inbox.org/git/CABPp-BFh=gL6RnbST2bgtynkij1Z5TMgAr1Via5_VyteF5eBMg@mail.gmail.com/
Martin
-->8--
Subject: merge-recursive: provide pair of unpack_trees_{start,finish}()
Rename git_merge_trees() to unpack_trees_start() and extract the call to discard_index() into a new function unpack_trees_finish(). As a result, these are called early resp. late in merge_trees(), making the resource handling clearer. The next commit will expand on that, teaching ..._finish() to free more memory. (So rather than moving the TODO-comment, just drop it, since it will be addressed soon enough.)
Also call ..._finish() when merge_trees() returns early.
--- merge-recursive.c | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-)
merge-recursive.c +15 -14
@@ -337,10 +337,10 @@ static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree)init_tree_desc (desc, tree->buffer, tree->size); } -static int git_merge_trees (struct merge_options *o, -struct tree *common, -struct tree *head, -struct tree *merge) +static int unpack_trees_start (struct merge_options *o, +struct tree *common, +struct tree *head, +struct tree *merge) {int rc;struct tree_desc t[3 ];
@@ -378,6 +378,11 @@ static int git_merge_trees(struct merge_options *o,return rc; } +static void unpack_trees_finish (struct merge_options *o) +{ +discard_index (&o->orig_index); +} +struct tree *write_tree_from_memory (struct merge_options *o) {struct tree *result =NULL ;
@@ -3079,13 +3084,14 @@ int merge_trees(struct merge_options *o,return 1 ; } - code =git_merge_trees (o, common, head, merge); + code =unpack_trees_start (o, common, head, merge);if (code !=0 ) {if (show (o,4 ) || o->call_depth)err (o,_ ("merging of trees %s and %s failed" ),oid_to_hex (&head->object.oid),oid_to_hex (&merge->object.oid)); +unpack_trees_finish (o);return -1 ; }
@@ -3138,20 +3144,15 @@ int merge_trees(struct merge_options *o,hashmap_free (&o->current_file_dir_set,1 ); -if (clean <0 ) +if (clean <0 ) { +unpack_trees_finish (o);return clean; + } }else clean =1 ; -/* Free the extra index left from git_merge_trees() */ -/* -* FIXME: Need to also data allocated by setup_unpack_trees_porcelain() -* tucked away in o->unpack_opts.msgs, but the problem is that only -* half of it refers to dynamically allocated data, while the other -* half points at static strings. -*/ -discard_index (&o->orig_index); +unpack_trees_finish (o);if (o->call_depth && !(*result =write_tree_from_memory (o)))return -1 ;
Signature · 1 line
2.17.0
Re: [PATCH 2/2] unpack_trees_options: free messages when done
Hi Martin,
Quoted 11 lines · Martin Ågren
-->8--
Subject: merge-recursive: provide pair ofunpack_trees_{start,finish}()Rename
git_merge_trees()tounpack_trees_start()and extract the call todiscard_index()into a new functionunpack_trees_finish(). As a result, these are called early resp. late inmerge_trees(), making the resource handling clearer. The next commit will expand on that, teaching..._finish()to free more memory. (So rather than moving the TODO-comment, just drop it, since it will be addressed soon enough.)
Quoted 1 line
Also call
..._finish()whenmerge_trees()returns early.
Looks good! It is missing a Signed-off-by: line, and you probably want to start a new thread that also includes the "next commit", but other than that it is pretty nice and ready for contributing, methinks.
Ciao,
Dscho
Re: [PATCH 2/2] unpack_trees_options: free messages when done
In reply to Martin ÅgrenHi Martin,
Quoted 7 lines · Martin Ågren
From: Elijah Newren <[email protected]>
Hi Elijah,
[Since this is leaving the topic of rename-detection in favour of leak-plugging, I'm shortening the cc-list a bit.]
Quoted 7 lines
Quoted 2 lines
So, instead, I'd like to see something like the below (built on top of my series):
Thanks a lot. I now have the below patch in my tree as a preparatory part of a three-patch series on top of your series. Since the gist of this patch is entirely your creation, is it ok if I place your Author:
and Signed-off-by: on it? Credit where credit is due.
Sure, I'm fine with either that or an Original-patch-by attribution.
Anyway, thanks for fleshing it out with the commit message and handling the early return cases. And for tackling the setup_unpack_trees_porcelain() memory leak.
Re: [PATCH 2/2] unpack_trees_options: free messages when done
In reply to Martin ÅgrenHi Martin,
Quoted 5 lines · Martin Ågren
As you noted elsewhere [1], Ben is also working in this area. I'd be perfectly happy to sit on these patches until both of your contributions come through to master.
[1] https://public-inbox.org/git/CABPp-BFh=gL6RnbST2bgtynkij1Z5TMgAr1Via5_VyteF5eBMg@mail.gmail.com/
Instead of waiting for these to come through to master, could you just submit based on the top of bp/merge-rename-config? I've got several other merge-recursive changes, some about ready to send and others in the works. I don't think any conflict yet, but I would rather avoid causing you any more waiting or conflicts and would rather just have both your and Ben's changes in pu and then I can just build mine on top of those. Besides, I want to see that FIXME go away and have fewer leaks. :-)
Thanks,
Elijah
v2 cover unpack_trees_options: free messages when done
Hi Elijah
Quoted 9 lines · Elijah Newren
Quoted 5 lines · Martin Ågren
As you noted elsewhere [1], Ben is also working in this area. I'd be perfectly happy to sit on these patches until both of your contributions come through to master.
[1] https://public-inbox.org/git/CABPp-BFh=gL6RnbST2bgtynkij1Z5TMgAr1Via5_VyteF5eBMg@mail.gmail.com/
Instead of waiting for these to come through to master, could you just submit based on the top of bp/merge-rename-config?
Sure, here goes. This is based on bp/merge-rename-config, gets rid of all leaks of memory allocated in setup_unpack_trees_porcelain() and cuts the number of leaks in the test-suite (i.e., the subset of the tests that I run) by around 10%.
Martin
Elijah Newren (1):
merge-recursive: provide pair of unpack_trees_{start,finish}()
Martin Ågren (2):
merge: setup opts later in checkout_fast_forward()
unpack_trees_options: free messages when done
unpack-trees.h | 5 +++++ builtin/checkout.c | 1 + merge-recursive.c | 30 ++++++++++++++++-------------- merge.c | 37 +++++++++++++++++++++---------------- unpack-trees.c | 11 +++++++++++ 5 files changed, 54 insertions(+), 30 deletions(-)
Signature · 1 line
2.17.0.583.g9a75a153ac
PATCH v2 1/3 merge: setup `opts` later in `checkout_fast_forward()`
After we initialize the various fields in opts but before we actually use them, we might return early. Move the initialization further down, to immediately before we use opts.
This limits the scope of opts and will help a later commit fix a memory leak without having to worry about those early returns.
This patch is best viewed using something like this (note the tab!):
--color-moved --anchored=" trees[nr_trees] = parse_tree_indirect"
--- merge.c | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-)
merge.c +18 -16
@@ -94,23 +94,7 @@ int checkout_fast_forward(const struct object_id *head,return -1 ;memset (&trees,0 ,sizeof (trees)); -memset (&opts,0 ,sizeof (opts));memset (&t,0 ,sizeof (t)); -if (overwrite_ignore) { -memset (&dir,0 ,sizeof (dir)); - dir.flags |=DIR_SHOW_IGNORED ; -setup_standard_excludes (&dir); - opts.dir = &dir; - } - - opts.head_idx =1 ; - opts.src_index = &the_index; - opts.dst_index = &the_index; - opts.update =1 ; - opts.verbose_update =1 ; - opts.merge =1 ; - opts.fn = twoway_merge; -setup_unpack_trees_porcelain (&opts,"merge" ); trees[nr_trees] =parse_tree_indirect (head);if (!trees[nr_trees++]) {
@@ -126,6 +110,24 @@ int checkout_fast_forward(const struct object_id *head,parse_tree (trees[i]);init_tree_desc (t+i, trees[i]->buffer, trees[i]->size); } + +memset (&opts,0 ,sizeof (opts)); +if (overwrite_ignore) { +memset (&dir,0 ,sizeof (dir)); + dir.flags |=DIR_SHOW_IGNORED ; +setup_standard_excludes (&dir); + opts.dir = &dir; + } + + opts.head_idx =1 ; + opts.src_index = &the_index; + opts.dst_index = &the_index; + opts.update =1 ; + opts.verbose_update =1 ; + opts.merge =1 ; + opts.fn = twoway_merge; +setup_unpack_trees_porcelain (&opts,"merge" ); +if (unpack_trees (nr_trees, t, &opts)) {rollback_lock_file (&lock_file);return -1 ;
Signature · 1 line
2.17.0.583.g9a75a153ac
Re: [PATCH v2 1/3] merge: setup `opts` later in `checkout_fast_forward()`
+ Jonathan Tan for a side discussion on anchoring.
Quoted 3 lines · Martin Ågren
This patch is best viewed using something like this (note the tab!):
--color-moved --anchored=" trees[nr_trees] =parse_tree_indirect"
Heh! Having a "is best viewed" paragraph is the new shiny thing in commit messages as 'git log origin/pu --grep "is best viewed"' tells me.
Regarding the anchoring, I wonder if we can improve it by ignoring whitespaces or just looking for substrings, or by allowing regexes or ...
Thanks,
Stefan
Re: [PATCH v2 1/3] merge: setup `opts` later in `checkout_fast_forward()`
Quoted 7 lines · Stefan Beller
Quoted 3 lines · Martin Ågren
This patch is best viewed using something like this (note the tab!):
--color-moved --anchored=" trees[nr_trees] =parse_tree_indirect"Heh! Having a "is best viewed" paragraph is the new shiny thing in commit messages as 'git log origin/pu --grep "is best viewed"' tells me.
:-)
Quoted 2 lines
Regarding the anchoring, I wonder if we can improve it by ignoring whitespaces or just looking for substrings, or by allowing regexes or ...
FWIW, because my first naive attempt failed (for some reason I did not consider the leading tab part of the "line" so I did not provide it), I had the same thought. Ignoring leading whitespace seemed easy enough in the implementation.
Then I started thinking about all the ways in which whitespace can be ignored. My reaction in the end was to not try and open that can right there and then. I did not think about regexes.
I guess this boils down to the usage. Copying the line to anchor on from an editor could run into these kind of whitespace-issues, and shell escaping. Typing an anchor could become easier with regexes since one could skip typing common substrings and just anchor on /unique-part/.
Martin
Re: [PATCH v2 1/3] merge: setup `opts` later in `checkout_fast_forward()`
Quoted 23 lines · Martin Ågren
Quoted 7 lines · Stefan Beller
Quoted 3 lines · Martin Ågren
This patch is best viewed using something like this (note the tab!):
--color-moved --anchored=" trees[nr_trees] =parse_tree_indirect"Heh! Having a "is best viewed" paragraph is the new shiny thing in commit messages as 'git log origin/pu --grep "is best viewed"' tells me.
:-)
Quoted 2 lines
Regarding the anchoring, I wonder if we can improve it by ignoring whitespaces or just looking for substrings, or by allowing regexes or ...
FWIW, because my first naive attempt failed (for some reason I did not consider the leading tab part of the "line" so I did not provide it), I had the same thought. Ignoring leading whitespace seemed easy enough in the implementation.
Then I started thinking about all the ways in which whitespace can be ignored. My reaction in the end was to not try and open that can right there and then. I did not think about regexes.
Quoted 6 lines
I guess this boils down to the usage. Copying the line to anchor on from an editor could run into these kind of whitespace-issues, and shell escaping. Typing an anchor could become easier with regexes since one could skip typing common substrings and just anchor on /unique-part/.
Martin
Simpler approach is to just match substring instead. Then, the user can decide how much of the string is required to get the anchor they wanted.
Thanks,
Jake
Re: [PATCH v2 1/3] merge: setup `opts` later in `checkout_fast_forward()`
In reply to Stefan BellerQuoted 7 lines · Stefan Beller
+ Jonathan Tan for a side discussion on anchoring.
Quoted 3 lines · Martin Ågren
This patch is best viewed using something like this (note the tab!):
--color-moved --anchored=" trees[nr_trees] =parse_tree_indirect"
Quoted 8 lines
Heh! Having a "is best viewed" paragraph is the new shiny thing in commit messages as 'git log origin/pu --grep "is best viewed"' tells me.
Regarding the anchoring, I wonder if we can improve it by ignoring whitespaces or just looking for substrings, or by allowing regexes or ...
Thanks,
Stefan
I think expanding it to be regexp would be nicest. To be honest, I already thought it was substring based....
It'd be *really* cool if we had a way for a commit messages (or maybe notes?) to indicate the anchor so that git show could (optionally) figure out the anchor automatically. It's been REALLY useful for me when showing diffs to be able to provide a better idea of what a human *actually* did vs what the smallest diff was.
Thanks,
Jake
Re: [PATCH v2 1/3] merge: setup `opts` later in `checkout_fast_forward()`
In reply to Martin ÅgrenQuoted 9 lines · Martin Ågren
After we initialize the various fields in
optsbut before we actually use them, we might return early. Move the initialization further down, to immediately before we useopts.This limits the scope of
optsand will help a later commit fix a memory leak without having to worry about those early returns.This patch is best viewed using something like this (note the tab!):
--color-moved --anchored=" trees[nr_trees] =parse_tree_indirect"
This side remark is interesting because it totally depends on how you look at it. I think "initialize opts late" and "attempt to parse the trees first and fail early" are the sides of the same coin, and the diff shown without the anchor matches the latter, which is also perfectly acceptable interpretation of what this patch does.
Re: [PATCH v2 1/3] merge: setup `opts` later in `checkout_fast_forward()`
Quoted 12 lines · Junio C Hamano
Quoted 9 lines · Martin Ågren
After we initialize the various fields in
optsbut before we actually use them, we might return early. Move the initialization further down, to immediately before we useopts.This limits the scope of
optsand will help a later commit fix a memory leak without having to worry about those early returns.This patch is best viewed using something like this (note the tab!):
--color-moved --anchored=" trees[nr_trees] =parse_tree_indirect"
Quoted 7 lines
This side remark is interesting because it totally depends on how you look at it. I think "initialize opts late" and "attempt to parse the trees first and fail early" are the sides of the same coin, and the diff shown without the anchor matches the latter, which is also perfectly acceptable interpretation of what this patch does.
Yes. I like that we have tools available to show diffs in different hopefully meaningful ways.
I happen to like when the diff matches my mental map of the change after reading the commit message, so having the author indicate how best to view it is useful, but definitely cool to see that we can get different interpretations.
Thanks,
Jake
PATCH v2 2/3 merge-recursive: provide pair of `unpack_trees_{start,finish}()`
In reply to Martin ÅgrenFrom: Elijah Newren <[email protected]>
Rename git_merge_trees() to unpack_trees_start() and extract the call to discard_index() into a new function unpack_trees_finish(). As a result, these are called early resp. late in merge_trees(), making the resource handling clearer. The next commit will expand on that, teaching ..._finish() to free more memory. (So rather than moving the FIXME-comment, just drop it, since it will be addressed soon enough.)
Also call ..._finish() when merge_trees() returns early.
--- merge-recursive.c | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-)
merge-recursive.c +15 -14
@@ -337,10 +337,10 @@ static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree)init_tree_desc (desc, tree->buffer, tree->size); } -static int git_merge_trees (struct merge_options *o, -struct tree *common, -struct tree *head, -struct tree *merge) +static int unpack_trees_start (struct merge_options *o, +struct tree *common, +struct tree *head, +struct tree *merge) {int rc;struct tree_desc t[3 ];
@@ -379,6 +379,11 @@ static int git_merge_trees(struct merge_options *o,return rc; } +static void unpack_trees_finish (struct merge_options *o) +{ +discard_index (&o->orig_index); +} +struct tree *write_tree_from_memory (struct merge_options *o) {struct tree *result =NULL ;
@@ -3088,13 +3093,14 @@ int merge_trees(struct merge_options *o,return 1 ; } - code =git_merge_trees (o, common, head, merge); + code =unpack_trees_start (o, common, head, merge);if (code !=0 ) {if (show (o,4 ) || o->call_depth)err (o,_ ("merging of trees %s and %s failed" ),oid_to_hex (&head->object.oid),oid_to_hex (&merge->object.oid)); +unpack_trees_finish (o);return -1 ; }
@@ -3147,20 +3153,15 @@ int merge_trees(struct merge_options *o,hashmap_free (&o->current_file_dir_set,1 ); -if (clean <0 ) +if (clean <0 ) { +unpack_trees_finish (o);return clean; + } }else clean =1 ; -/* Free the extra index left from git_merge_trees() */ -/* -* FIXME: Need to also free data allocated by -* setup_unpack_trees_porcelain() tucked away in o->unpack_opts.msgs, -* but the problem is that only half of it refers to dynamically -* allocated data, while the other half points at static strings. -*/ -discard_index (&o->orig_index); +unpack_trees_finish (o);if (o->call_depth && !(*result =write_tree_from_memory (o)))return -1 ;
Signature · 1 line
2.17.0.583.g9a75a153ac
PATCH v2 3/3 unpack_trees_options: free messages when done
In reply to Martin ÅgrenThe strings allocated in setup_unpack_trees_porcelain() are never freed. Provide a function clear_unpack_trees_porcelain() to do so and call it where we use setup_unpack_trees_porcelain(). The only non-trivial user is unpack_trees_start(), where we should place the new call in unpack_trees_finish().
The opts string array contains multiple copies of the same pointers. Be careful to only free each pointer once, then zeroize the whole array so that we do not leave any dangling pointers.
Note that we only take responsibility for the memory allocated in setup_unpack_trees_porcelain() and not any other members of the struct unpack_trees_options.
--- unpack-trees.h | 5 +++++ builtin/checkout.c | 1 + merge-recursive.c | 1 + merge.c | 3 +++ unpack-trees.c | 11 +++++++++++ 5 files changed, 21 insertions(+)
unpack-trees.h +5 -0
@@ -33,6 +33,11 @@ enum unpack_trees_error_types {void setup_unpack_trees_porcelain (struct unpack_trees_options *opts,const char *cmd); +/* +* Frees resources allocated by setup_unpack_trees_porcelain(). +*/ +extern void clear_unpack_trees_porcelain (struct unpack_trees_options *opts); +struct unpack_trees_options {unsigned int reset, merge,
builtin/checkout.c +1 -0
@@ -526,6 +526,7 @@ static int merge_working_tree(const struct checkout_opts *opts,init_tree_desc (&trees[1 ], tree->buffer, tree->size); ret =unpack_trees (2 , trees, &topts); +clear_unpack_trees_porcelain (&topts);if (ret ==-1 ) {/* * Unpack couldn't do a trivial merge; either
merge-recursive.c +1 -0
@@ -382,6 +382,7 @@ static int unpack_trees_start(struct merge_options *o,static void unpack_trees_finish (struct merge_options *o) {discard_index (&o->orig_index); +clear_unpack_trees_porcelain (&o->unpack_opts); }struct tree *write_tree_from_memory (struct merge_options *o)
merge.c +3 -0
@@ -130,8 +130,11 @@ int checkout_fast_forward(const struct object_id *head,if (unpack_trees (nr_trees, t, &opts)) {rollback_lock_file (&lock_file); +clear_unpack_trees_porcelain (&opts);return -1 ; } +clear_unpack_trees_porcelain (&opts); +if (write_locked_index (&the_index, &lock_file,COMMIT_LOCK ))return error (_ ("unable to write new index file" ));return 0 ;
unpack-trees.c +11 -0
@@ -179,6 +179,17 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts, opts->unpack_rejects[i].strdup_strings =1 ; } +void clear_unpack_trees_porcelain (struct unpack_trees_options *opts) +{ +char **msgs = (char **)opts->msgs; + +free (msgs[ERROR_WOULD_OVERWRITE ]); +free (msgs[ERROR_WOULD_LOSE_UNTRACKED_REMOVED ]); +free (msgs[ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN ]); + +memset (opts->msgs,0 ,sizeof (opts->msgs)); +} +static int do_add_entry (struct unpack_trees_options *o,struct cache_entry *ce,unsigned int set,unsigned int clear) {
Signature · 1 line
2.17.0.583.g9a75a153ac
Re: [PATCH v2 3/3] unpack_trees_options: free messages when done
Quoted 9 lines · Martin Ågren
The strings allocated in
setup_unpack_trees_porcelain()are never freed. Provide a functionclear_unpack_trees_porcelain()to do so and call it where we usesetup_unpack_trees_porcelain(). The only non-trivial user isunpack_trees_start(), where we should place the new call inunpack_trees_finish().The
optsstring array contains multiple copies of the same pointers. Be careful to only free each pointer once, then zeroize the whole array so that we do not leave any dangling pointers.
The verb to make it zero or fill it with zero is "to zero", I would think.
To be honest I am not sure if I like the way this change is done. The clear_unpack_trees_porcelain() function has too intimate knowledge of what happens inside the setup_unpack_trees_porcelain() function; it not just knows which fields are always allocated but which are duplicates, which must be double checked for updates whenever the latter gets modified, yet there is no large warning sign painted in red in the latter, so it is easy to change the latter and invalidate the assumption the former makes by mistake, leading to new leaks and/or double freeing.
I wonder if an approach that is longer-term a bit more maintainable is to add a new string-list instance to opts, save these xstrfmt()'ed messages to it when setup_unpack_trees_porcelain() create them, and then make clear_unpack_trees_porcelain() pay *no* attention to msg[] array and the positions of these allocated messages and duplicates but just reclaim the resources held in that string-list, or something like that.
Re: [PATCH v2 3/3] unpack_trees_options: free messages when done
Quoted 6 lines · Junio C Hamano
Quoted 3 lines · Martin Ågren
The
optsstring array contains multiple copies of the same pointers. Be careful to only free each pointer once, then zeroize the whole array so that we do not leave any dangling pointers.
Quoted 7 lines
I wonder if an approach that is longer-term a bit more maintainable is to add a new string-list instance to opts, save these xstrfmt()'ed messages to it when
setup_unpack_trees_porcelain()create them, and then makeclear_unpack_trees_porcelain()pay *no* attention to msg[] array and the positions of these allocated messages and duplicates but just reclaim the resources held in that string-list, or something like that.
Thank you for thoughts and this suggestion. I will try this out, hopefully later today.
Martin
v3 cover unpack_trees_options: free messages when done
This is a reroll of my attempt at freeing the memory allocated by setup_unpack_trees_porcelain(). The first two patches are identical to v2. The third patch no longer relies on rather intimate knowledge of which strings are on the heap and which pointers are duplicates. Instead, as suggested by Junio, I keep a separate string-list of strings to free. That should make things more future-proof.
v2: https://public-inbox.org/git/[email protected]/
Martin
Elijah Newren (1):
merge-recursive: provide pair of unpack_trees_{start,finish}()
Martin Ågren (2):
merge: setup opts later in checkout_fast_forward()
unpack_trees_options: free messages when done
unpack-trees.h | 6 ++++++ builtin/checkout.c | 1 + merge-recursive.c | 30 ++++++++++++++++-------------- merge.c | 35 ++++++++++++++++++++--------------- unpack-trees.c | 23 +++++++++++++++++++---- 5 files changed, 62 insertions(+), 33 deletions(-)
Signature · 1 line
2.17.0.840.g5d83f92caf
PATCH v3 1/3 merge: setup `opts` later in `checkout_fast_forward()`
After we initialize the various fields in opts but before we actually use them, we might return early. Move the initialization further down, to immediately before we use opts.
This limits the scope of opts and will help a later commit fix a memory leak without having to worry about those early returns.
This patch is best viewed using something like this (note the tab!):
--color-moved --anchored=" trees[nr_trees] = parse_tree_indirect"
--- merge.c | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-)
merge.c +17 -15
@@ -94,8 +94,24 @@ int checkout_fast_forward(const struct object_id *head,return -1 ;memset (&trees,0 ,sizeof (trees)); -memset (&opts,0 ,sizeof (opts));memset (&t,0 ,sizeof (t)); + + trees[nr_trees] =parse_tree_indirect (head); +if (!trees[nr_trees++]) { +rollback_lock_file (&lock_file); +return -1 ; + } + trees[nr_trees] =parse_tree_indirect (remote); +if (!trees[nr_trees++]) { +rollback_lock_file (&lock_file); +return -1 ; + } +for (i =0 ; i < nr_trees; i++) { +parse_tree (trees[i]); +init_tree_desc (t+i, trees[i]->buffer, trees[i]->size); + } + +memset (&opts,0 ,sizeof (opts));if (overwrite_ignore) {memset (&dir,0 ,sizeof (dir)); dir.flags |=DIR_SHOW_IGNORED ;
@@ -112,20 +128,6 @@ int checkout_fast_forward(const struct object_id *head, opts.fn = twoway_merge;setup_unpack_trees_porcelain (&opts,"merge" ); - trees[nr_trees] =parse_tree_indirect (head); -if (!trees[nr_trees++]) { -rollback_lock_file (&lock_file); -return -1 ; - } - trees[nr_trees] =parse_tree_indirect (remote); -if (!trees[nr_trees++]) { -rollback_lock_file (&lock_file); -return -1 ; - } -for (i =0 ; i < nr_trees; i++) { -parse_tree (trees[i]); -init_tree_desc (t+i, trees[i]->buffer, trees[i]->size); - }if (unpack_trees (nr_trees, t, &opts)) {rollback_lock_file (&lock_file);return -1 ;
Signature · 1 line
2.17.0.840.g5d83f92caf
PATCH v3 2/3 merge-recursive: provide pair of `unpack_trees_{start,finish}()`
In reply to Martin ÅgrenFrom: Elijah Newren <[email protected]>
Rename git_merge_trees() to unpack_trees_start() and extract the call to discard_index() into a new function unpack_trees_finish(). As a result, these are called early resp. late in merge_trees(), making the resource handling clearer. The next commit will expand on that, teaching ..._finish() to free more memory. (So rather than moving the FIXME-comment, just drop it, since it will be addressed soon enough.)
Also call ..._finish() when merge_trees() returns early.
--- merge-recursive.c | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-)
merge-recursive.c +15 -14
@@ -337,10 +337,10 @@ static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree)init_tree_desc (desc, tree->buffer, tree->size); } -static int git_merge_trees (struct merge_options *o, -struct tree *common, -struct tree *head, -struct tree *merge) +static int unpack_trees_start (struct merge_options *o, +struct tree *common, +struct tree *head, +struct tree *merge) {int rc;struct tree_desc t[3 ];
@@ -379,6 +379,11 @@ static int git_merge_trees(struct merge_options *o,return rc; } +static void unpack_trees_finish (struct merge_options *o) +{ +discard_index (&o->orig_index); +} +struct tree *write_tree_from_memory (struct merge_options *o) {struct tree *result =NULL ;
@@ -3088,13 +3093,14 @@ int merge_trees(struct merge_options *o,return 1 ; } - code =git_merge_trees (o, common, head, merge); + code =unpack_trees_start (o, common, head, merge);if (code !=0 ) {if (show (o,4 ) || o->call_depth)err (o,_ ("merging of trees %s and %s failed" ),oid_to_hex (&head->object.oid),oid_to_hex (&merge->object.oid)); +unpack_trees_finish (o);return -1 ; }
@@ -3147,20 +3153,15 @@ int merge_trees(struct merge_options *o,hashmap_free (&o->current_file_dir_set,1 ); -if (clean <0 ) +if (clean <0 ) { +unpack_trees_finish (o);return clean; + } }else clean =1 ; -/* Free the extra index left from git_merge_trees() */ -/* -* FIXME: Need to also free data allocated by -* setup_unpack_trees_porcelain() tucked away in o->unpack_opts.msgs, -* but the problem is that only half of it refers to dynamically -* allocated data, while the other half points at static strings. -*/ -discard_index (&o->orig_index); +unpack_trees_finish (o);if (o->call_depth && !(*result =write_tree_from_memory (o)))return -1 ;
Signature · 1 line
2.17.0.840.g5d83f92caf
PATCH v3 3/3 unpack_trees_options: free messages when done
In reply to Martin ÅgrenThe strings allocated in setup_unpack_trees_porcelain() are never freed. Provide a function clear_unpack_trees_porcelain() to do so and call it where we use setup_unpack_trees_porcelain(). The only non-trivial user is unpack_trees_start(), where we should place the new call in unpack_trees_finish().
We keep the string pointers in an array, mixing pointers to static memory and memory that we allocate on the heap. We also keep several copies of the individual pointers. So we need to make sure that we do not free what we must not free and that we do not double-free. Keep the unique, heap-allocated pointers in a separate string list, to make the freeing safe and future-proof.
Zero the whole array of string pointers to make sure that we do not leave any dangling pointers.
Note that we only take responsibility for the memory allocated in setup_unpack_trees_porcelain() and not any other members of the struct unpack_trees_options.
--- unpack-trees.h | 6 ++++++ builtin/checkout.c | 1 + merge-recursive.c | 1 + merge.c | 3 +++ unpack-trees.c | 23 +++++++++++++++++++---- 5 files changed, 30 insertions(+), 4 deletions(-)
unpack-trees.h +6 -0
@@ -33,6 +33,11 @@ enum unpack_trees_error_types {void setup_unpack_trees_porcelain (struct unpack_trees_options *opts,const char *cmd); +/* +* Frees resources allocated by setup_unpack_trees_porcelain(). +*/ +void clear_unpack_trees_porcelain (struct unpack_trees_options *opts); +struct unpack_trees_options {unsigned int reset, merge,
@@ -57,6 +62,7 @@ struct unpack_trees_options {struct pathspec *pathspec;merge_fn_t fn;const char *msgs[NB_UNPACK_TREES_ERROR_TYPES ]; +struct string_list msgs_to_free;/* * Store error messages in an array, each case * corresponding to a error message type
builtin/checkout.c +1 -0
@@ -526,6 +526,7 @@ static int merge_working_tree(const struct checkout_opts *opts,init_tree_desc (&trees[1 ], tree->buffer, tree->size); ret =unpack_trees (2 , trees, &topts); +clear_unpack_trees_porcelain (&topts);if (ret ==-1 ) {/* * Unpack couldn't do a trivial merge; either
merge-recursive.c +1 -0
@@ -382,6 +382,7 @@ static int unpack_trees_start(struct merge_options *o,static void unpack_trees_finish (struct merge_options *o) {discard_index (&o->orig_index); +clear_unpack_trees_porcelain (&o->unpack_opts); }struct tree *write_tree_from_memory (struct merge_options *o)
merge.c +3 -0
@@ -130,8 +130,11 @@ int checkout_fast_forward(const struct object_id *head,if (unpack_trees (nr_trees, t, &opts)) {rollback_lock_file (&lock_file); +clear_unpack_trees_porcelain (&opts);return -1 ; } +clear_unpack_trees_porcelain (&opts); +if (write_locked_index (&the_index, &lock_file,COMMIT_LOCK ))return error (_ ("unable to write new index file" ));return 0 ;
unpack-trees.c +19 -4
@@ -103,6 +103,8 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts,const char **msgs = opts->msgs;const char *msg; + opts->msgs_to_free.strdup_strings =0 ; +if (!strcmp (cmd,"checkout" )) msg = advice_commit_before_merge ? _("Your local changes to the following files would be overwritten by checkout:\n%%s"
@@ -118,8 +120,9 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts, ?_ ("Your local changes to the following files would be overwritten by %s:\n%%s" "Please commit your changes or stash them before you %s." ) :_ ("Your local changes to the following files would be overwritten by %s:\n%%s" ); - msgs[ERROR_WOULD_OVERWRITE ] = msgs[ERROR_NOT_UPTODATE_FILE ] = -xstrfmt (msg, cmd, cmd); + msg =xstrfmt (msg, cmd, cmd); + msgs[ERROR_WOULD_OVERWRITE ] = msgs[ERROR_NOT_UPTODATE_FILE ] = msg; +string_list_append (&opts->msgs_to_free, msg); msgs[ERROR_NOT_UPTODATE_DIR ] =_ ("Updating the following directories would lose untracked files in them:\n%s" );
@@ -139,7 +142,9 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts, ?_ ("The following untracked working tree files would be removed by %s:\n%%s" "Please move or remove them before you %s." ) :_ ("The following untracked working tree files would be removed by %s:\n%%s" ); - msgs[ERROR_WOULD_LOSE_UNTRACKED_REMOVED ] =xstrfmt (msg, cmd, cmd); + msg =xstrfmt (msg, cmd, cmd); + msgs[ERROR_WOULD_LOSE_UNTRACKED_REMOVED ] = msg; +string_list_append (&opts->msgs_to_free, msg);if (!strcmp (cmd,"checkout" )) msg = advice_commit_before_merge
@@ -156,7 +161,9 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts, ?_ ("The following untracked working tree files would be overwritten by %s:\n%%s" "Please move or remove them before you %s." ) :_ ("The following untracked working tree files would be overwritten by %s:\n%%s" ); - msgs[ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN ] =xstrfmt (msg, cmd, cmd); + msg =xstrfmt (msg, cmd, cmd); + msgs[ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN ] = msg; +string_list_append (&opts->msgs_to_free, msg);/* * Special case: ERROR_BIND_OVERLAP refers to a pair of paths, we
@@ -179,6 +186,14 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts, opts->unpack_rejects[i].strdup_strings =1 ; } +void clear_unpack_trees_porcelain (struct unpack_trees_options *opts) +{ + opts->msgs_to_free.strdup_strings =1 ; +string_list_clear (&opts->msgs_to_free,0 ); + +memset (opts->msgs,0 ,sizeof (opts->msgs)); +} +static int do_add_entry (struct unpack_trees_options *o,struct cache_entry *ce,unsigned int set,unsigned int clear) {
Signature · 1 line
2.17.0.840.g5d83f92caf
Re: [PATCH v3 3/3] unpack_trees_options: free messages when done
Quoted 5 lines · Martin Ågren
unpack-trees.c +0
-0
unpack-trees.c void setup_unpack_trees_porcelain(struct unpack_trees_options *opts,
Quoted 10 lines
unpack-trees.c +6
-0@@ -103,6 +103,8 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts,const char **msgs = opts->msgs;const char *msg; + opts->msgs_to_free.strdup_strings =0 ; + +void clear_unpack_trees_porcelain (struct unpack_trees_options *opts) +{ + opts->msgs_to_free.strdup_strings =1 ; +string_list_clear (&opts->msgs_to_free,0 );
I like this string_list approach much better, but it's too bad we have to go through these contortions with the strdup flag to get the memory ownership right.
If we had a string_list_appendf(), then we could just leave that flag alone and this:
unpack-trees.c void setup_unpack_trees_porcelain(struct unpack_trees_options *opts, · line 125
Quoted 9 lines
unpack-trees.c +3
-2@@ -118,8 +120,9 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts, ?_ ("Your local changes to the following files would be overwritten by %s:\n%%s" "Please commit your changes or stash them before you %s." ) :_ ("Your local changes to the following files would be overwritten by %s:\n%%s" ); - msgs[ERROR_WOULD_OVERWRITE ] = msgs[ERROR_NOT_UPTODATE_FILE ] = -xstrfmt (msg, cmd, cmd); + msg =xstrfmt (msg, cmd, cmd); + msgs[ERROR_WOULD_OVERWRITE ] = msgs[ERROR_NOT_UPTODATE_FILE ] = msg; +string_list_append (&opts->msgs_to_free, msg);
would become:
msgs[ERROR_WOULD_OVERWRITE] = msgs[ERROR_NOUPTODATE_FILE] =
string_list_appendf(&opts->msgs_to_free, msg, cmd, cmd)->string;
I don't know if that's worth it or not (I suspect that there are other places where appendf would be handy, but I didn't poke around).
-Peff
Re: [PATCH v3 3/3] unpack_trees_options: free messages when done
Quoted 37 lines · Jeff King
Quoted 5 lines · Martin Ågren
unpack-trees.c +0
-0unpack-trees.c void setup_unpack_trees_porcelain(struct unpack_trees_options *opts,
Quoted 10 lines
unpack-trees.c +6
-0@@ -103,6 +103,8 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts,const char **msgs = opts->msgs;const char *msg; + opts->msgs_to_free.strdup_strings =0 ; + +void clear_unpack_trees_porcelain (struct unpack_trees_options *opts) +{ + opts->msgs_to_free.strdup_strings =1 ; +string_list_clear (&opts->msgs_to_free,0 );I like this
string_listapproach much better, but it's too bad we have to go through these contortions with the strdup flag to get the memory ownership right.If we had a
string_list_appendf(), then we could just leave that flag alone and this:unpack-trees.c void setup_unpack_trees_porcelain(struct unpack_trees_options *opts, · line 125
Quoted 9 lines
unpack-trees.c +3
-2@@ -118,8 +120,9 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts, ?_ ("Your local changes to the following files would be overwritten by %s:\n%%s" "Please commit your changes or stash them before you %s." ) :_ ("Your local changes to the following files would be overwritten by %s:\n%%s" ); - msgs[ERROR_WOULD_OVERWRITE ] = msgs[ERROR_NOT_UPTODATE_FILE ] = -xstrfmt (msg, cmd, cmd); + msg =xstrfmt (msg, cmd, cmd); + msgs[ERROR_WOULD_OVERWRITE ] = msgs[ERROR_NOT_UPTODATE_FILE ] = msg; +string_list_append (&opts->msgs_to_free, msg);would become:
Quoted 5 lines
msgs[ERROR_WOULD_OVERWRITE] = msgs[ERROR_NOUPTODATE_FILE] = string_list_appendf(&opts->msgs_to_free, msg, cmd, cmd)->string;I don't know if that's worth it or not (I suspect that there are other places where appendf would be handy, but I didn't poke around).
The strdup_strings=1 immediately before calling string_list_clear()
has been used in one other place in merge-recursive.c, and tripped up
the reviewer requiring a big code comment to explain it. (See the very
end of https://public-inbox.org/git/CABPp-BGh7QTTfu3kgH4KO5DrrXiQjtrNhx_uaQsB6fHXT+9hLQ@mail.gmail.com/
). So there's already one other place in merge-recursive.c that might
benefit from such a change.
A quick search shows about half a dozen other sites throughout the code that are doing something similar:
$ git grep -3 strdup_strings | grep -B 1 string_list_clear bisect.c: refs_for_removal.strdup_strings = 1; bisect.c- string_list_clear(&refs_for_removal, 0); -- builtin/shortlog.c: onelines->strdup_strings = 1; builtin/shortlog.c- string_list_clear(onelines, 0); -- builtin/shortlog.c: log->list.strdup_strings = 1; builtin/shortlog.c- string_list_clear(&log->list, 1); -- mailmap.c: me->namemap.strdup_strings = 1; mailmap.c- string_list_clear_func(&me->namemap, free_mailmap_info); -- mailmap.c: map->strdup_strings = 1; mailmap.c- string_list_clear_func(map, free_mailmap_entry); -- merge-recursive.c: entry->possible_new_dirs.strdup_strings = 1; merge-recursive.c- string_list_clear(&entry->possible_new_dirs, 1); -- revision.c: revs->notes_opt.extra_notes_refs.strdup_strings = 1; revision.c- string_list_clear(&revs->notes_opt.extra_notes_refs, 0);
Maybe someone wants to tackle that as a separate patch series? (Maybe we make it a micro-project for future GSoC'ers?)
Re: [PATCH v3 3/3] unpack_trees_options: free messages when done
Quoted 8 lines · Elijah Newren
Quoted 7 lines
would become:
msgs[ERROR_WOULD_OVERWRITE] = msgs[ERROR_NOUPTODATE_FILE] = string_list_appendf(&opts->msgs_to_free, msg, cmd, cmd)->string;I don't know if that's worth it or not (I suspect that there are other places where appendf would be handy, but I didn't poke around).
Quoted 6 lines
The strdup_strings=1 immediately before calling
string_list_clear()
has been used in one other place inmerge-recursive.c, and tripped up
the reviewer requiring a big code comment to explain it. (See the very
end of https://public-inbox.org/git/CABPp-BGh7QTTfu3kgH4KO5DrrXiQjtrNhx_uaQsB6fHXT+9hLQ@mail.gmail.com/
). So there's already one other place inmerge-recursive.cthat might
benefit from such a change.
Thanks. I knew I had seen such hackery before, but it's nice to have a specific site that would benefit.
IMHO the "nodup" variant of string_list is quite often a sign that things are more complicated than they need to be. Even in cases that are truly pointing to existing strings, is the complication really worth saving a few strdups? Perhaps sometimes, but I have a suspicion it's mostly premature optimization.
Quoted 2 lines
Maybe someone wants to tackle that as a separate patch series? (Maybe we make it a micro-project for future GSoC'ers?)
Yeah, I'm fine with these patches if somebody wants to do it separately. It would be a good micro-project, but I'd also be just as happy if somebody did it before next year. :)
-Peff
Re: [PATCH v3 3/3] unpack_trees_options: free messages when done
Quoted 9 lines · Jeff King
Quoted 7 lines · Elijah Newren
Quoted 7 lines
would become:
msgs[ERROR_WOULD_OVERWRITE] = msgs[ERROR_NOUPTODATE_FILE] = string_list_appendf(&opts->msgs_to_free, msg, cmd, cmd)->string;I don't know if that's worth it or not (I suspect that there are other places where appendf would be handy, but I didn't poke around).
This does poke at the string member, but there is precedent for doing that. That also feels much closer to the purpose of a string list than the fiddling with strdup_strings that I do in my patch.
I'll look into this over the weekend. Thanks for the suggestion.
Quoted 16 lines
Quoted 6 lines
The strdup_strings=1 immediately before calling
string_list_clear()
has been used in one other place inmerge-recursive.c, and tripped up
the reviewer requiring a big code comment to explain it. (See the very
end of https://public-inbox.org/git/CABPp-BGh7QTTfu3kgH4KO5DrrXiQjtrNhx_uaQsB6fHXT+9hLQ@mail.gmail.com/
). So there's already one other place inmerge-recursive.cthat might
benefit from such a change.Thanks. I knew I had seen such hackery before, but it's nice to have a specific site that would benefit.
IMHO the "nodup" variant of
string_listis quite often a sign that things are more complicated than they need to be. Even in cases that are truly pointing to existing strings, is the complication really worth saving a few strdups? Perhaps sometimes, but I have a suspicion it's mostly premature optimization.
Quoted 6 lines
Quoted 2 lines
Maybe someone wants to tackle that as a separate patch series? (Maybe we make it a micro-project for future GSoC'ers?)
Yeah, I'm fine with these patches if somebody wants to do it separately. It would be a good micro-project, but I'd also be just as happy if somebody did it before next year. :)
Obviously, I won't be tackling all of that now. I'll just look into making this final patch better and leave any further cleaning up for later.
Martin
v4 cover unpack_trees_options: free messages when done
This is v4 of my series for taking care of the memory allocated by setup_unpack_trees_porcelain(). As before, this is based on bp/merge-rename-config.
Quoted 11 lines · Martin Ågren
Quoted 8 lines · Jeff King
Quoted 8 lines
Quoted 8 lines
would become:
msgs[ERROR_WOULD_OVERWRITE] = msgs[ERROR_NOUPTODATE_FILE] = string_list_appendf(&opts->msgs_to_free, msg, cmd, cmd)->string;I don't know if that's worth it or not (I suspect that there are other places where appendf would be handy, but I didn't poke around).
I'll look into this over the weekend. Thanks for the suggestion.
The difference to v3 is indeed the new patch 3/4, which introduces string_list_appendf(). I think that makes patch 4/4 clearer and the resulting code less surprising.
There is an obvious candidate for using this new function in bisect.c, but I refrained from doing that conversion in this series. While converting that user to use this new function would be trivial and safe, such a change might not look entirely sane on its own. The reason is that the user does the whole strdup_strings-dance that I did in v3.
I think it would be much better to do that conversion as a part of a "let's not play with strdup_strings"-patch. I have one prepared and it looks quite ok to me. I should be able to be able to collect more strdup_string-cleanups soonish and submit a series later (say, when/if this here series has matured).
Elijah Newren (1):
merge-recursive: provide pair of unpack_trees_{start,finish}()
Martin Ågren (3):
merge: setup opts later in checkout_fast_forward()
string-list: provide string_list_appendf()
unpack_trees_options: free messages when done
string-list.h | 9 +++++++++ unpack-trees.h | 6 ++++++ builtin/checkout.c | 1 + merge-recursive.c | 30 ++++++++++++++++-------------- merge.c | 35 ++++++++++++++++++++--------------- string-list.c | 13 +++++++++++++ unpack-trees.c | 20 +++++++++++++++++--- 7 files changed, 82 insertions(+), 32 deletions(-)
Signature · 1 line
2.17.0.840.g5d83f92caf
PATCH v4 1/4 merge: setup `opts` later in `checkout_fast_forward()`
After we initialize the various fields in opts but before we actually use them, we might return early. Move the initialization further down, to immediately before we use opts.
This limits the scope of opts and will help a later commit fix a memory leak without having to worry about those early returns.
This patch is best viewed using something like this (note the tab!):
--color-moved --anchored=" trees[nr_trees] = parse_tree_indirect"
--- merge.c | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-)
merge.c +18 -16
@@ -94,23 +94,7 @@ int checkout_fast_forward(const struct object_id *head,return -1 ;memset (&trees,0 ,sizeof (trees)); -memset (&opts,0 ,sizeof (opts));memset (&t,0 ,sizeof (t)); -if (overwrite_ignore) { -memset (&dir,0 ,sizeof (dir)); - dir.flags |=DIR_SHOW_IGNORED ; -setup_standard_excludes (&dir); - opts.dir = &dir; - } - - opts.head_idx =1 ; - opts.src_index = &the_index; - opts.dst_index = &the_index; - opts.update =1 ; - opts.verbose_update =1 ; - opts.merge =1 ; - opts.fn = twoway_merge; -setup_unpack_trees_porcelain (&opts,"merge" ); trees[nr_trees] =parse_tree_indirect (head);if (!trees[nr_trees++]) {
@@ -126,6 +110,24 @@ int checkout_fast_forward(const struct object_id *head,parse_tree (trees[i]);init_tree_desc (t+i, trees[i]->buffer, trees[i]->size); } + +memset (&opts,0 ,sizeof (opts)); +if (overwrite_ignore) { +memset (&dir,0 ,sizeof (dir)); + dir.flags |=DIR_SHOW_IGNORED ; +setup_standard_excludes (&dir); + opts.dir = &dir; + } + + opts.head_idx =1 ; + opts.src_index = &the_index; + opts.dst_index = &the_index; + opts.update =1 ; + opts.verbose_update =1 ; + opts.merge =1 ; + opts.fn = twoway_merge; +setup_unpack_trees_porcelain (&opts,"merge" ); +if (unpack_trees (nr_trees, t, &opts)) {rollback_lock_file (&lock_file);return -1 ;
Signature · 1 line
2.17.0.840.g5d83f92caf
PATCH v4 2/4 merge-recursive: provide pair of `unpack_trees_{start,finish}()`
In reply to Martin ÅgrenFrom: Elijah Newren <[email protected]>
Rename git_merge_trees() to unpack_trees_start() and extract the call to discard_index() into a new function unpack_trees_finish(). As a result, these are called early resp. late in merge_trees(), making the resource handling clearer. A later commit will expand on that, teaching ..._finish() to free more memory. (So rather than moving the FIXME-comment, just drop it, since it will be addressed soon enough.)
Also call ..._finish() when merge_trees() returns early.
--- merge-recursive.c | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-)
merge-recursive.c +15 -14
@@ -337,10 +337,10 @@ static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree)init_tree_desc (desc, tree->buffer, tree->size); } -static int git_merge_trees (struct merge_options *o, -struct tree *common, -struct tree *head, -struct tree *merge) +static int unpack_trees_start (struct merge_options *o, +struct tree *common, +struct tree *head, +struct tree *merge) {int rc;struct tree_desc t[3 ];
@@ -379,6 +379,11 @@ static int git_merge_trees(struct merge_options *o,return rc; } +static void unpack_trees_finish (struct merge_options *o) +{ +discard_index (&o->orig_index); +} +struct tree *write_tree_from_memory (struct merge_options *o) {struct tree *result =NULL ;
@@ -3088,13 +3093,14 @@ int merge_trees(struct merge_options *o,return 1 ; } - code =git_merge_trees (o, common, head, merge); + code =unpack_trees_start (o, common, head, merge);if (code !=0 ) {if (show (o,4 ) || o->call_depth)err (o,_ ("merging of trees %s and %s failed" ),oid_to_hex (&head->object.oid),oid_to_hex (&merge->object.oid)); +unpack_trees_finish (o);return -1 ; }
@@ -3147,20 +3153,15 @@ int merge_trees(struct merge_options *o,hashmap_free (&o->current_file_dir_set,1 ); -if (clean <0 ) +if (clean <0 ) { +unpack_trees_finish (o);return clean; + } }else clean =1 ; -/* Free the extra index left from git_merge_trees() */ -/* -* FIXME: Need to also free data allocated by -* setup_unpack_trees_porcelain() tucked away in o->unpack_opts.msgs, -* but the problem is that only half of it refers to dynamically -* allocated data, while the other half points at static strings. -*/ -discard_index (&o->orig_index); +unpack_trees_finish (o);if (o->call_depth && !(*result =write_tree_from_memory (o)))return -1 ;
Signature · 1 line
2.17.0.840.g5d83f92caf
PATCH v4 3/4 string-list: provide `string_list_appendf()`
In reply to Martin ÅgrenAdd a function string_list_appendf(list, fmt, ...) to the string-list API. The next commit will add a user.
This function naturally ignores the strdup_strings-setting and always appends a freshly allocated string. Thus, using this function with strdup_strings = 0 risks making ownership unclear and leaking memory. With strdup_strings = 1 on the other hand, we can easily add formatted strings without going through string_list_append_nodup() or playing with strdup_strings.
--- string-list.h | 9 +++++++++ string-list.c | 13 +++++++++++++ 2 files changed, 22 insertions(+)
string-list.h +9 -0
@@ -208,6 +208,15 @@ void string_list_remove_duplicates(struct string_list *sorted_list, int free_uti*/ struct string_list_item *string_list_append (struct string_list *list,const char *string); +/** +* Add formatted string to the end of `list`. This function ignores +* the value of `list->strdup_strings` and always appends a freshly +* allocated string, so you will probably not want to use it with +* `strdup_strings = 0`. +*/ +struct string_list_item *string_list_appendf (struct string_list *list, +const char *fmt, ...); +/** * Like string_list_append(), except string is never copied. When * list->strdup_strings is set, this function can be used to hand
string-list.c +13 -0
@@ -224,6 +224,19 @@ struct string_list_item *string_list_append(struct string_list *list, list->strdup_strings ? xstrdup(string) : (char *)string); } +struct string_list_item *string_list_appendf (struct string_list *list, +const char *fmt, ...) +{ +struct string_list_item *retval; +va_list ap; + +va_start (ap, fmt); + retval =string_list_append_nodup (list,xstrvfmt (fmt, ap)); +va_end (ap); + +return retval; +} +static int cmp_items (const void *a,const void *b,void *ctx) {compare_strings_fn cmp = ctx;
Signature · 1 line
2.17.0.840.g5d83f92caf
Re: [PATCH v4 3/4] string-list: provide `string_list_appendf()`
string-list.h void string_list_remove_duplicates(struct string_list *sorted_list, int free_uti · line 219
Quoted 9 lines · Martin Ågren
string-list.h +9
-0+/** +* Add formatted string to the end of `list`. This function ignores +* the value of `list->strdup_strings` and always appends a freshly +* allocated string, so you will probably not want to use it with +* `strdup_strings = 0`. +*/ +struct string_list_item *string_list_appendf (struct string_list *list, +const char *fmt, ...); +
Would it make sense to verify that strdup_strings == 0? I guess we'd have to use die or BUG(), but that would mean that the program could crash..
I doubt this could be verified at compilation time....
Thanks,
Jake
Re*: [PATCH v4 3/4] string-list: provide `string_list_appendf()`
Quoted 14 lines · Jacob Keller
Review
Quoted 9 lines · Martin Ågren
(quoted diff) +9
-0+/** + * Add formatted string to the end of `list`. This function ignores + * the value of `list->strdup_strings` and always appends a freshly + * allocated string, so you will probably not want to use it with + * `strdup_strings = 0`. + */ +struct string_list_item *string_list_appendf(struct string_list *list, + const char *fmt, ...); +Would it make sense to verify that
strdup_strings== 0? I guess we'd have to use die orBUG(), but that would mean that the program could crash..
It probably is clear to readers that any reasonable implementation of *_appendf() will create a new and unique string, as the point of *f() is to give a customized instantiation of fmt string for given parameters. So it would be natural to expect that the storage that holds the generated string will belong to the list. We _could_ make it honor strdup_strings and make one extra copy when strdup_strings is set to true, but the only effect such a stupid implementation has is to unnecessarily leak ;-)
I think it is probably OK to check and BUG() when strdup_strings==0, but such a check means that we now declare that a string list must either borrow all of its strings from elsewhere or own all of its strings itself, and mixture is not allowed.
The (overly) flexible string_list API could be used to mix both borrowed and owned strings (an obvious strategy to do this without leaking and crashing is to use the .util field to mark which ones are owned and which ones are borrowed), so there might already be current users of the API that violates that rule.
I have a feeling that argv_array might be a better fit for the purpose of keeping track of to_free[] strings in the context of this series. Moving away from string_list would allow us to sidestep the storage ownership issues the API has, and we do not need the .util thing string_list gives us (which is one distinct advantage string_list has over argv_array, if the application needs that feature).
We would need to make _pushf() and friends return "const char *" if we go that route to make the resulting API more useful, though.
-- >8 --
Subject: argv-array: return the pushed string from argv_push*()
Such an API change allows us to use an argv_array this way:
struct argv_array to_free = ARGV_ARRAY_INIT;
const char *msg;
if (some condition) {
msg = "constant string message";
... other logic ...
} else {
msg = argv_pushf(&to_free, "format %s", var);
}
... use "msg" ...
... do other things ...
argv_clear(&to_free);Note that argv_array_pushl() and argv_array_pushv() are used to push one or more strings with a single call, so we do not return any one of these strings from these two functions in order to reduce the chance to misuse the API.
--- argv-array.c | 6 ++++-- argv-array.h | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-)
argv-array.c +4 -2
@@ -21,12 +21,13 @@ static void argv_array_push_nodup(struct argv_array *array, const char *value) array->argv[array->argc] =NULL ; } -void argv_array_push (struct argv_array *array,const char *value) +const char *argv_array_push (struct argv_array *array,const char *value) {argv_array_push_nodup (array,xstrdup (value)); +return array->argv[array->argc -1 ]; } -void argv_array_pushf (struct argv_array *array,const char *fmt, ...) +const char *argv_array_pushf (struct argv_array *array,const char *fmt, ...) {va_list ap;struct strbuf v =STRBUF_INIT ;
@@ -36,6 +37,7 @@ void argv_array_pushf(struct argv_array *array, const char *fmt, ...)va_end (ap);argv_array_push_nodup (array,strbuf_detach (&v,NULL )); +return array->argv[array->argc -1 ]; }void argv_array_pushl (struct argv_array *array, ...)
argv-array.h +2 -2
@@ -12,9 +12,9 @@ struct argv_array {#define ARGV_ARRAY_INIT { empty_argv, 0, 0 }void argv_array_init (struct argv_array *); -void argv_array_push (struct argv_array *,const char *); +const char *argv_array_push (struct argv_array *,const char *); __attribute__((format (printf,2 ,3 ))) -void argv_array_pushf (struct argv_array *,const char *fmt, ...); +const char *argv_array_pushf (struct argv_array *,const char *fmt, ...);LAST_ARG_MUST_BE_NULL void argv_array_pushl(struct argv_array *, ...);void argv_array_pushv (struct argv_array *,const char **);
Re: Re*: [PATCH v4 3/4] string-list: provide `string_list_appendf()`
Quoted 9 lines · Junio C Hamano
I have a feeling that
argv_arraymight be a better fit for the purpose of keeping track of to_free[] strings in the context of this series. Moving away fromstring_listwould allow us to sidestep the storage ownership issues the API has, and we do not need the .util thingstring_listgives us (which is one distinct advantagestring_listhas overargv_array, if the application needs that feature).We would need to make
_pushf()and friends return "const char *" if we go that route to make the resulting API more useful, though.
... and redoing the 4/4 patch using argv_array_pushf() makes the result look like this, which does not look too bad.
-- >8 --
From: Junio C Hamano <[email protected]>
Subject: [PATCH] unpack_trees_options: keep track of owned messages with argv_array
Instead of the string_list API, which is overly flexible and require callers to be careful about memory ownership issues, use the argv_array API that always takes ownership to redo the earlier commit.
--- unpack-trees.c | 16 ++++++---------- unpack-trees.h | 4 ++-- 2 files changed, 8 insertions(+), 12 deletions(-)
unpack-trees.c +6 -10
@@ -1,5 +1,6 @@#define NO_THE_INDEX_COMPATIBILITY_MACROS #include "cache.h" +#include "argv-array.h" #include "repository.h" #include "config.h" #include "dir.h"
@@ -103,11 +104,7 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts,const char **msgs = opts->msgs;const char *msg; -/* -* As we add strings using `...appendf()`, this does not matter, -* but when we clear the string list, we want them to be freed. -*/ - opts->msgs_to_free.strdup_strings =1 ; +argv_array_init (&opts->msgs_to_free);if (!strcmp (cmd,"checkout" )) msg = advice_commit_before_merge
@@ -125,7 +122,7 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts, "Please commit your changes or stash them before you %s.") : _("Your local changes to the following files would be overwritten by %s:\n%%s"); msgs[ERROR_WOULD_OVERWRITE ] = msgs[ERROR_NOT_UPTODATE_FILE ] = -string_list_appendf (&opts->msgs_to_free, msg, cmd, cmd)->string; +argv_array_pushf (&opts->msgs_to_free, msg, cmd, cmd); msgs[ERROR_NOT_UPTODATE_DIR ] =_ ("Updating the following directories would lose untracked files in them:\n%s" );
@@ -146,7 +143,7 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts, "Please move or remove them before you %s.") : _("The following untracked working tree files would be removed by %s:\n%%s"); msgs[ERROR_WOULD_LOSE_UNTRACKED_REMOVED ] = -string_list_appendf (&opts->msgs_to_free, msg, cmd, cmd)->string; +argv_array_pushf (&opts->msgs_to_free, msg, cmd, cmd);if (!strcmp (cmd,"checkout" )) msg = advice_commit_before_merge
@@ -164,7 +161,7 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts, "Please move or remove them before you %s.") : _("The following untracked working tree files would be overwritten by %s:\n%%s"); msgs[ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN ] = -string_list_appendf (&opts->msgs_to_free, msg, cmd, cmd)->string; +argv_array_pushf (&opts->msgs_to_free, msg, cmd, cmd);/* * Special case: ERROR_BIND_OVERLAP refers to a pair of paths, we
@@ -189,8 +186,7 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts,void clear_unpack_trees_porcelain (struct unpack_trees_options *opts) { -string_list_clear (&opts->msgs_to_free,0 ); -memset (opts->msgs,0 ,sizeof (opts->msgs)); +argv_array_clear (&opts->msgs_to_free); } static int do_add_entry(struct unpack_trees_options *o, struct cache_entry *ce,
unpack-trees.h +2 -2
@@ -2,7 +2,7 @@#define UNPACK_TREES_H #include "tree-walk.h" -#include "string-list.h" +#include "argv-array.h" #define MAX_UNPACK_TREES 8
@@ -62,7 +62,7 @@ struct unpack_trees_options {struct pathspec *pathspec;merge_fn_t fn;const char *msgs[NB_UNPACK_TREES_ERROR_TYPES ]; -struct string_list msgs_to_free; +struct argv_array msgs_to_free;/* * Store error messages in an array, each case * corresponding to a error message type
Signature · 1 line
2.17.0-582-gccdcbd54c4
Re: Re*: [PATCH v4 3/4] string-list: provide `string_list_appendf()`
Quoted 9 lines · Junio C Hamano
Quoted 7 lines · Junio C Hamano
I have a feeling that
argv_arraymight be a better fit for the purpose of keeping track of to_free[] strings in the context of this series. Moving away fromstring_listwould allow us to sidestep the storage ownership issues the API has, and we do not need the .util thingstring_listgives us (which is one distinct advantagestring_listhas overargv_array, if the application needs that feature).
Quoted 5 lines
Quoted 2 lines
We would need to make
_pushf()and friends return "const char *" if we go that route to make the resulting API more useful, though.... and redoing the 4/4 patch using
argv_array_pushf()makes the result look like this, which does not look too bad.
Agreed.
-Peff
v5 cover unpack_trees_options: free messages when done
In reply to Junio C HamanoQuoted 9 lines · Junio C Hamano
Quoted 7 lines · Junio C Hamano
I have a feeling that
argv_arraymight be a better fit for the purpose of keeping track of to_free[] strings in the context of this series. Moving away fromstring_listwould allow us to sidestep the storage ownership issues the API has, and we do not need the .util thingstring_listgives us (which is one distinct advantagestring_listhas overargv_array, if the application needs that feature).
Quoted 5 lines
Quoted 2 lines
We would need to make
_pushf()and friends return "const char *" if we go that route to make the resulting API more useful, though.... and redoing the 4/4 patch using
argv_array_pushf()makes the result look like this, which does not look too bad.
Thanks to Jacob, Junio and Peff for comments on the previous iteration.
I've taken the six patches that Junio has queued and rebuilt the series to get rid of the new and possibly bug-prone function that no-one uses once the series is over.
That is, I've replaced the string_list_appendf()-patch with Junio's argv_push*()-patch, then squashed Junio's "redoing the 4/4"-patch into patch 4/4 -- with the exception of keeping the memset(opts->msgs, ...) which I suspect was mistakenly dropped.
Again, thanks for all the helpful comments and patches pointing me in the right direction.
Martin
Elijah Newren (1):
merge-recursive: provide pair of unpack_trees_{start,finish}()
Junio C Hamano (1):
argv-array: return the pushed string from argv_push*()
Martin Ågren (2):
merge: setup opts later in checkout_fast_forward()
unpack_trees_options: free messages when done
argv-array.h | 4 ++-- unpack-trees.h | 8 +++++++- argv-array.c | 6 ++++-- builtin/checkout.c | 1 + merge-recursive.c | 30 ++++++++++++++++-------------- merge.c | 35 ++++++++++++++++++++--------------- unpack-trees.c | 17 ++++++++++++++--- 7 files changed, 64 insertions(+), 37 deletions(-)
Signature · 1 line
2.17.0.840.g5d83f92caf
PATCH v5 1/4 merge: setup `opts` later in `checkout_fast_forward()`
After we initialize the various fields in opts but before we actually use them, we might return early. Move the initialization further down, to immediately before we use opts.
This limits the scope of opts and will help a later commit fix a memory leak without having to worry about those early returns.
This patch is best viewed using something like this (note the tab!):
--color-moved --anchored=" trees[nr_trees] = parse_tree_indirect"
--- merge.c | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-)
merge.c +17 -15
@@ -94,8 +94,24 @@ int checkout_fast_forward(const struct object_id *head,return -1 ;memset (&trees,0 ,sizeof (trees)); -memset (&opts,0 ,sizeof (opts));memset (&t,0 ,sizeof (t)); + + trees[nr_trees] =parse_tree_indirect (head); +if (!trees[nr_trees++]) { +rollback_lock_file (&lock_file); +return -1 ; + } + trees[nr_trees] =parse_tree_indirect (remote); +if (!trees[nr_trees++]) { +rollback_lock_file (&lock_file); +return -1 ; + } +for (i =0 ; i < nr_trees; i++) { +parse_tree (trees[i]); +init_tree_desc (t+i, trees[i]->buffer, trees[i]->size); + } + +memset (&opts,0 ,sizeof (opts));if (overwrite_ignore) {memset (&dir,0 ,sizeof (dir)); dir.flags |=DIR_SHOW_IGNORED ;
@@ -112,20 +128,6 @@ int checkout_fast_forward(const struct object_id *head, opts.fn = twoway_merge;setup_unpack_trees_porcelain (&opts,"merge" ); - trees[nr_trees] =parse_tree_indirect (head); -if (!trees[nr_trees++]) { -rollback_lock_file (&lock_file); -return -1 ; - } - trees[nr_trees] =parse_tree_indirect (remote); -if (!trees[nr_trees++]) { -rollback_lock_file (&lock_file); -return -1 ; - } -for (i =0 ; i < nr_trees; i++) { -parse_tree (trees[i]); -init_tree_desc (t+i, trees[i]->buffer, trees[i]->size); - }if (unpack_trees (nr_trees, t, &opts)) {rollback_lock_file (&lock_file);return -1 ;
Signature · 1 line
2.17.0.840.g5d83f92caf
PATCH v5 2/4 merge-recursive: provide pair of `unpack_trees_{start,finish}()`
In reply to Martin ÅgrenFrom: Elijah Newren <[email protected]>
Rename git_merge_trees() to unpack_trees_start() and extract the call to discard_index() into a new function unpack_trees_finish(). As a result, these are called early resp. late in merge_trees(), making the resource handling clearer. A later commit will expand on that, teaching ..._finish() to free more memory. (So rather than moving the FIXME-comment, just drop it, since it will be addressed soon enough.)
Also call ..._finish() when merge_trees() returns early.
--- merge-recursive.c | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-)
merge-recursive.c +15 -14
@@ -337,10 +337,10 @@ static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree)init_tree_desc (desc, tree->buffer, tree->size); } -static int git_merge_trees (struct merge_options *o, -struct tree *common, -struct tree *head, -struct tree *merge) +static int unpack_trees_start (struct merge_options *o, +struct tree *common, +struct tree *head, +struct tree *merge) {int rc;struct tree_desc t[3 ];
@@ -379,6 +379,11 @@ static int git_merge_trees(struct merge_options *o,return rc; } +static void unpack_trees_finish (struct merge_options *o) +{ +discard_index (&o->orig_index); +} +struct tree *write_tree_from_memory (struct merge_options *o) {struct tree *result =NULL ;
@@ -3088,13 +3093,14 @@ int merge_trees(struct merge_options *o,return 1 ; } - code =git_merge_trees (o, common, head, merge); + code =unpack_trees_start (o, common, head, merge);if (code !=0 ) {if (show (o,4 ) || o->call_depth)err (o,_ ("merging of trees %s and %s failed" ),oid_to_hex (&head->object.oid),oid_to_hex (&merge->object.oid)); +unpack_trees_finish (o);return -1 ; }
@@ -3147,20 +3153,15 @@ int merge_trees(struct merge_options *o,hashmap_free (&o->current_file_dir_set,1 ); -if (clean <0 ) +if (clean <0 ) { +unpack_trees_finish (o);return clean; + } }else clean =1 ; -/* Free the extra index left from git_merge_trees() */ -/* -* FIXME: Need to also free data allocated by -* setup_unpack_trees_porcelain() tucked away in o->unpack_opts.msgs, -* but the problem is that only half of it refers to dynamically -* allocated data, while the other half points at static strings. -*/ -discard_index (&o->orig_index); +unpack_trees_finish (o);if (o->call_depth && !(*result =write_tree_from_memory (o)))return -1 ;
Signature · 1 line
2.17.0.840.g5d83f92caf
PATCH v5 3/4 argv-array: return the pushed string from argv_push*()
In reply to Martin ÅgrenFrom: Junio C Hamano <[email protected]>
Such an API change allows us to use an argv_array this way:
struct argv_array to_free = ARGV_ARRAY_INIT;
const char *msg;
if (some condition) {
msg = "constant string message";
... other logic ...
} else {
msg = argv_pushf(&to_free, "format %s", var);
}
... use "msg" ...
... do other things ...
argv_clear(&to_free);Note that argv_array_pushl() and argv_array_pushv() are used to push one or more strings with a single call, so we do not return any one of these strings from these two functions in order to reduce the chance to misuse the API.
--- argv-array.h | 4 ++-- argv-array.c | 6 ++++-- 2 files changed, 6 insertions(+), 4 deletions(-)
argv-array.h +2 -2
@@ -12,9 +12,9 @@ struct argv_array {#define ARGV_ARRAY_INIT { empty_argv, 0, 0 }void argv_array_init (struct argv_array *); -void argv_array_push (struct argv_array *,const char *); +const char *argv_array_push (struct argv_array *,const char *); __attribute__((format (printf,2 ,3 ))) -void argv_array_pushf (struct argv_array *,const char *fmt, ...); +const char *argv_array_pushf (struct argv_array *,const char *fmt, ...);LAST_ARG_MUST_BE_NULL void argv_array_pushl(struct argv_array *, ...);void argv_array_pushv (struct argv_array *,const char **);
argv-array.c +4 -2
@@ -21,12 +21,13 @@ static void argv_array_push_nodup(struct argv_array *array, const char *value) array->argv[array->argc] =NULL ; } -void argv_array_push (struct argv_array *array,const char *value) +const char *argv_array_push (struct argv_array *array,const char *value) {argv_array_push_nodup (array,xstrdup (value)); +return array->argv[array->argc -1 ]; } -void argv_array_pushf (struct argv_array *array,const char *fmt, ...) +const char *argv_array_pushf (struct argv_array *array,const char *fmt, ...) {va_list ap;struct strbuf v =STRBUF_INIT ;
@@ -36,6 +37,7 @@ void argv_array_pushf(struct argv_array *array, const char *fmt, ...)va_end (ap);argv_array_push_nodup (array,strbuf_detach (&v,NULL )); +return array->argv[array->argc -1 ]; }void argv_array_pushl (struct argv_array *array, ...)
Signature · 1 line
2.17.0.840.g5d83f92caf
PATCH v5 4/4 unpack_trees_options: free messages when done
In reply to Martin ÅgrenThe strings allocated in setup_unpack_trees_porcelain() are never freed. Provide a function clear_unpack_trees_porcelain() to do so and call it where we use setup_unpack_trees_porcelain(). The only non-trivial user is unpack_trees_start(), where we should place the new call in unpack_trees_finish().
We keep the string pointers in an array, mixing pointers to static memory and memory that we allocate on the heap. We also keep several copies of the individual pointers. So we need to make sure that we do not free what we must not free and that we do not double-free. Let a separate argv_array take ownership of all the strings we create so that we can easily free them.
Zero the whole array of string pointers to make sure that we do not leave any dangling pointers.
Note that we only take responsibility for the memory allocated in setup_unpack_trees_porcelain() and not any other members of the struct unpack_trees_options.
--- unpack-trees.h | 8 +++++++- builtin/checkout.c | 1 + merge-recursive.c | 1 + merge.c | 3 +++ unpack-trees.c | 17 ++++++++++++++--- 5 files changed, 26 insertions(+), 4 deletions(-)
unpack-trees.h +7 -1
@@ -2,7 +2,7 @@#define UNPACK_TREES_H #include "tree-walk.h" -#include "string-list.h" +#include "argv-array.h" #define MAX_UNPACK_TREES 8
@@ -33,6 +33,11 @@ enum unpack_trees_error_types {void setup_unpack_trees_porcelain (struct unpack_trees_options *opts,const char *cmd); +/* +* Frees resources allocated by setup_unpack_trees_porcelain(). +*/ +void clear_unpack_trees_porcelain (struct unpack_trees_options *opts); +struct unpack_trees_options {unsigned int reset, merge,
@@ -57,6 +62,7 @@ struct unpack_trees_options {struct pathspec *pathspec;merge_fn_t fn;const char *msgs[NB_UNPACK_TREES_ERROR_TYPES ]; +struct argv_array msgs_to_free;/* * Store error messages in an array, each case * corresponding to a error message type
builtin/checkout.c +1 -0
@@ -526,6 +526,7 @@ static int merge_working_tree(const struct checkout_opts *opts,init_tree_desc (&trees[1 ], tree->buffer, tree->size); ret =unpack_trees (2 , trees, &topts); +clear_unpack_trees_porcelain (&topts);if (ret ==-1 ) {/* * Unpack couldn't do a trivial merge; either
merge-recursive.c +1 -0
@@ -382,6 +382,7 @@ static int unpack_trees_start(struct merge_options *o,static void unpack_trees_finish (struct merge_options *o) {discard_index (&o->orig_index); +clear_unpack_trees_porcelain (&o->unpack_opts); }struct tree *write_tree_from_memory (struct merge_options *o)
merge.c +3 -0
@@ -130,8 +130,11 @@ int checkout_fast_forward(const struct object_id *head,if (unpack_trees (nr_trees, t, &opts)) {rollback_lock_file (&lock_file); +clear_unpack_trees_porcelain (&opts);return -1 ; } +clear_unpack_trees_porcelain (&opts); +if (write_locked_index (&the_index, &lock_file,COMMIT_LOCK ))return error (_ ("unable to write new index file" ));return 0 ;
unpack-trees.c +14 -3
@@ -1,5 +1,6 @@#define NO_THE_INDEX_COMPATIBILITY_MACROS #include "cache.h" +#include "argv-array.h" #include "repository.h" #include "config.h" #include "dir.h"
@@ -103,6 +104,8 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts,const char **msgs = opts->msgs;const char *msg; +argv_array_init (&opts->msgs_to_free); +if (!strcmp (cmd,"checkout" )) msg = advice_commit_before_merge ? _("Your local changes to the following files would be overwritten by checkout:\n%%s"
@@ -119,7 +122,7 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts, "Please commit your changes or stash them before you %s.") : _("Your local changes to the following files would be overwritten by %s:\n%%s"); msgs[ERROR_WOULD_OVERWRITE ] = msgs[ERROR_NOT_UPTODATE_FILE ] = -xstrfmt (msg, cmd, cmd); +argv_array_pushf (&opts->msgs_to_free, msg, cmd, cmd); msgs[ERROR_NOT_UPTODATE_DIR ] =_ ("Updating the following directories would lose untracked files in them:\n%s" );
@@ -139,7 +142,8 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts, ?_ ("The following untracked working tree files would be removed by %s:\n%%s" "Please move or remove them before you %s." ) :_ ("The following untracked working tree files would be removed by %s:\n%%s" ); - msgs[ERROR_WOULD_LOSE_UNTRACKED_REMOVED ] =xstrfmt (msg, cmd, cmd); + msgs[ERROR_WOULD_LOSE_UNTRACKED_REMOVED ] = +argv_array_pushf (&opts->msgs_to_free, msg, cmd, cmd);if (!strcmp (cmd,"checkout" )) msg = advice_commit_before_merge
@@ -156,7 +160,8 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts, ?_ ("The following untracked working tree files would be overwritten by %s:\n%%s" "Please move or remove them before you %s." ) :_ ("The following untracked working tree files would be overwritten by %s:\n%%s" ); - msgs[ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN ] =xstrfmt (msg, cmd, cmd); + msgs[ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN ] = +argv_array_pushf (&opts->msgs_to_free, msg, cmd, cmd);/* * Special case: ERROR_BIND_OVERLAP refers to a pair of paths, we
@@ -179,6 +184,12 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts, opts->unpack_rejects[i].strdup_strings =1 ; } +void clear_unpack_trees_porcelain (struct unpack_trees_options *opts) +{ +argv_array_clear (&opts->msgs_to_free); +memset (opts->msgs,0 ,sizeof (opts->msgs)); +} +static int do_add_entry (struct unpack_trees_options *o,struct cache_entry *ce,unsigned int set,unsigned int clear) {
Signature · 1 line
2.17.0.840.g5d83f92caf
Re: [PATCH v5 0/4] unpack_trees_options: free messages when done
In reply to Martin ÅgrenQuoted 7 lines · Martin Ågren
That is, I've replaced the
string_list_appendf()-patch with Junio'sargv_push*()-patch, then squashed Junio's "redoing the 4/4"-patch into patch 4/4 -- with the exception of keeping thememset(opts->msgs, ...)which I suspect was mistakenly dropped.Again, thanks for all the helpful comments and patches pointing me in the right direction.
I like it. Thanks for seeing it through. That was a lot of back-and-forth for a small cleanup, but I hope we've established a pattern that can be used elsewhere.
-Peff
Re: [PATCH v5 0/4] unpack_trees_options: free messages when done
In reply to Martin ÅgrenQuoted 3 lines · Martin Ågren
I've taken the six patches that Junio has queued and rebuilt the series to get rid of the new and possibly bug-prone function that no-one uses once the series is over.
Hmph, this unfortunately depends on 'next', which means we cannot merge it down to 'maint' later to fix these leaks. I guess it is not a huge deal, though. We've lived with these message leaks for quite some time now and earth still kept rotating ;-)
Re: [PATCH v5 0/4] unpack_trees_options: free messages when done
Quoted 10 lines · Junio C Hamano
Quoted 3 lines · Martin Ågren
I've taken the six patches that Junio has queued and rebuilt the series to get rid of the new and possibly bug-prone function that no-one uses once the series is over.
Hmph, this unfortunately depends on 'next', which means we cannot merge it down to 'maint' later to fix these leaks. I guess it is not a huge deal, though. We've lived with these message leaks for quite some time now and earth still kept rotating ;-)
Oh, what was I thinking. This, just like its previous rounds, is on top of bp/merge-rename-config^0 and it is expected *not* to be mergeable to 'maint' (or 'master', for that matter, at least not yet).
Will queue. Thanks.
Re: [PATCH v5 0/4] unpack_trees_options: free messages when done
Quoted 11 lines · Junio C Hamano
Quoted 4 lines · Junio C Hamano
Hmph, this unfortunately depends on 'next', which means we cannot merge it down to 'maint' later to fix these leaks. I guess it is not a huge deal, though. We've lived with these message leaks for quite some time now and earth still kept rotating ;-)
Oh, what was I thinking. This, just like its previous rounds, is on top of bp/merge-rename-config^0 and it is expected *not* to be mergeable to 'maint' (or 'master', for that matter, at least not yet).
Right. The reason it depends on that topic is the user in merge-recursive.c. Other than patch 2 and a small part of patch 4, this should be mergeable to 'master' (as I recall) and probably also to 'maint'. I suppose this series could have been done as three patches to fix all users except one, then one or two patches to fix merge-recursive.c.
That would have allowed merging the first part of the series to 'maint'. (Maybe not to fix the leaking as such, but to keep 'maint' more up to date with 'master' for easier merging of other topics?) If you'd prefer an ordering like that (now and/or in the future), just let me know.
Martin
Re: [PATCH v5 0/4] unpack_trees_options: free messages when done
Quoted 2 lines · Martin Ågren
(Maybe not to fix the leaking as such, but to keep 'maint' more up to date with 'master' for easier merging of other topics?)
I admit that I occasionally do such a "presumably no-op" merge to 'maint' out of sheer laziness, but in general I'd prefer to keep 'maint' quieter than that. As we do not have any repeated caller that calls unpack_trees unbounded number of times in a process, I think it is OK to limit this update only to 'master', especially at this late in the cycle.
Thanks.
Re: Re*: [PATCH v4 3/4] string-list: provide `string_list_appendf()`
In reply to Junio C HamanoQuoted 31 lines · Junio C Hamano
Quoted 14 lines · Jacob Keller
Review
Quoted 9 lines · Martin Ågren
(quoted diff) +9
-0+/** + * Add formatted string to the end of `list`. This function ignores + * the value of `list->strdup_strings` and always appends a freshly + * allocated string, so you will probably not want to use it with + * `strdup_strings = 0`. + */ +struct string_list_item *string_list_appendf(struct string_list *list, + const char *fmt, ...); +Would it make sense to verify that
strdup_strings== 0? I guess we'd have to use die orBUG(), but that would mean that the program could crash..It probably is clear to readers that any reasonable implementation of
*_appendf()will create a new and unique string, as the point of*f()is to give a customized instantiation of fmt string for given parameters. So it would be natural to expect that the storage that holds the generated string will belong to the list. We _could_ make it honorstrdup_stringsand make one extra copy whenstrdup_stringsis set to true, but the only effect such a stupid implementation has is to unnecessarily leak ;-)I think it is probably OK to check and
BUG()when strdup_strings==0, but such a check means that we now declare that a string list must either borrow all of its strings from elsewhere or own all of its strings itself, and mixture is not allowed.
Quoted 5 lines
The (overly) flexible
string_listAPI could be used to mix both borrowed and owned strings (an obvious strategy to do this without leaking and crashing is to use the .util field to mark which ones are owned and which ones are borrowed), so there might already be current users of the API that violates that rule.
IMHO such a mixed use is mildly crazy. At any rate, we would know that anybody using appendf() would not have this problem, since we are just introducing it now.
Quoted 6 lines
I have a feeling that
argv_arraymight be a better fit for the purpose of keeping track of to_free[] strings in the context of this series. Moving away fromstring_listwould allow us to sidestep the storage ownership issues the API has, and we do not need the .util thingstring_listgives us (which is one distinct advantagestring_listhas overargv_array, if the application needs that feature).
I do agree that argv_array is generally a better fit for most cases. Didn't we want to rename it to strarray or something? That's probably too much yak-shaving for this series, though. :)
Quoted 2 lines
We would need to make
_pushf()and friends return "const char *" if we go that route to make the resulting API more useful, though.
This is the first time I think that's been suggested, but I agree it's the only sensible thing for the functions to return.
Quoted 18 lines
-- >8 --
Subject: argv-array: return the pushed string from argv_push*()Such an API change allows us to use an
argv_arraythis way:struct argv_array to_free = ARGV_ARRAY_INIT; const char *msg; if (some condition) { msg = "constant string message"; ... other logic ... } else { msg = argv_pushf(&to_free, "format %s", var); } ... use "msg" ... ... do other things ... argv_clear(&to_free);
Quoted 7 lines
Note that
argv_array_pushl()andargv_array_pushv()are used to push one or more strings with a single call, so we do not return any one of these strings from these two functions in order to reduce the chance to misuse the API.Signed-off-by Junio C Hamano <[email protected]>---
Yup, this looks good to me.
-Peff
PATCH v4 4/4 unpack_trees_options: free messages when done
In reply to Martin ÅgrenThe strings allocated in setup_unpack_trees_porcelain() are never freed. Provide a function clear_unpack_trees_porcelain() to do so and call it where we use setup_unpack_trees_porcelain(). The only non-trivial user is unpack_trees_start(), where we should place the new call in unpack_trees_finish().
We keep the string pointers in an array, mixing pointers to static memory and memory that we allocate on the heap. We also keep several copies of the individual pointers. So we need to make sure that we do not free what we must not free and that we do not double-free. Keep the unique, heap-allocated pointers in a separate string list, to make the freeing safe and future-proof.
Zero the whole array of string pointers to make sure that we do not leave any dangling pointers.
Note that we only take responsibility for the memory allocated in setup_unpack_trees_porcelain() and not any other members of the struct unpack_trees_options.
--- unpack-trees.h | 6 ++++++ builtin/checkout.c | 1 + merge-recursive.c | 1 + merge.c | 3 +++ unpack-trees.c | 20 +++++++++++++++++--- 5 files changed, 28 insertions(+), 3 deletions(-)
unpack-trees.h +6 -0
@@ -33,6 +33,11 @@ enum unpack_trees_error_types {void setup_unpack_trees_porcelain (struct unpack_trees_options *opts,const char *cmd); +/* +* Frees resources allocated by setup_unpack_trees_porcelain(). +*/ +void clear_unpack_trees_porcelain (struct unpack_trees_options *opts); +struct unpack_trees_options {unsigned int reset, merge,
@@ -57,6 +62,7 @@ struct unpack_trees_options {struct pathspec *pathspec;merge_fn_t fn;const char *msgs[NB_UNPACK_TREES_ERROR_TYPES ]; +struct string_list msgs_to_free;/* * Store error messages in an array, each case * corresponding to a error message type
builtin/checkout.c +1 -0
@@ -526,6 +526,7 @@ static int merge_working_tree(const struct checkout_opts *opts,init_tree_desc (&trees[1 ], tree->buffer, tree->size); ret =unpack_trees (2 , trees, &topts); +clear_unpack_trees_porcelain (&topts);if (ret ==-1 ) {/* * Unpack couldn't do a trivial merge; either
merge-recursive.c +1 -0
@@ -382,6 +382,7 @@ static int unpack_trees_start(struct merge_options *o,static void unpack_trees_finish (struct merge_options *o) {discard_index (&o->orig_index); +clear_unpack_trees_porcelain (&o->unpack_opts); }struct tree *write_tree_from_memory (struct merge_options *o)
merge.c +3 -0
@@ -130,8 +130,11 @@ int checkout_fast_forward(const struct object_id *head,if (unpack_trees (nr_trees, t, &opts)) {rollback_lock_file (&lock_file); +clear_unpack_trees_porcelain (&opts);return -1 ; } +clear_unpack_trees_porcelain (&opts); +if (write_locked_index (&the_index, &lock_file,COMMIT_LOCK ))return error (_ ("unable to write new index file" ));return 0 ;
unpack-trees.c +17 -3
@@ -103,6 +103,12 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts,const char **msgs = opts->msgs;const char *msg; +/* +* As we add strings using `...appendf()`, this does not matter, +* but when we clear the string list, we want them to be freed. +*/ + opts->msgs_to_free.strdup_strings =1 ; +if (!strcmp (cmd,"checkout" )) msg = advice_commit_before_merge ? _("Your local changes to the following files would be overwritten by checkout:\n%%s"
@@ -119,7 +125,7 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts, "Please commit your changes or stash them before you %s.") : _("Your local changes to the following files would be overwritten by %s:\n%%s"); msgs[ERROR_WOULD_OVERWRITE ] = msgs[ERROR_NOT_UPTODATE_FILE ] = -xstrfmt (msg, cmd, cmd); +string_list_appendf (&opts->msgs_to_free, msg, cmd, cmd)->string; msgs[ERROR_NOT_UPTODATE_DIR ] =_ ("Updating the following directories would lose untracked files in them:\n%s" );
@@ -139,7 +145,8 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts, ?_ ("The following untracked working tree files would be removed by %s:\n%%s" "Please move or remove them before you %s." ) :_ ("The following untracked working tree files would be removed by %s:\n%%s" ); - msgs[ERROR_WOULD_LOSE_UNTRACKED_REMOVED ] =xstrfmt (msg, cmd, cmd); + msgs[ERROR_WOULD_LOSE_UNTRACKED_REMOVED ] = +string_list_appendf (&opts->msgs_to_free, msg, cmd, cmd)->string;if (!strcmp (cmd,"checkout" )) msg = advice_commit_before_merge
@@ -156,7 +163,8 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts, ?_ ("The following untracked working tree files would be overwritten by %s:\n%%s" "Please move or remove them before you %s." ) :_ ("The following untracked working tree files would be overwritten by %s:\n%%s" ); - msgs[ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN ] =xstrfmt (msg, cmd, cmd); + msgs[ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN ] = +string_list_appendf (&opts->msgs_to_free, msg, cmd, cmd)->string;/* * Special case: ERROR_BIND_OVERLAP refers to a pair of paths, we
@@ -179,6 +187,12 @@ void setup_unpack_trees_porcelain(struct unpack_trees_options *opts, opts->unpack_rejects[i].strdup_strings =1 ; } +void clear_unpack_trees_porcelain (struct unpack_trees_options *opts) +{ +string_list_clear (&opts->msgs_to_free,0 ); +memset (opts->msgs,0 ,sizeof (opts->msgs)); +} +static int do_add_entry (struct unpack_trees_options *o,struct cache_entry *ce,unsigned int set,unsigned int clear) {
Signature · 1 line
2.17.0.840.g5d83f92caf
Re: [PATCH v2 0/3] unpack_trees_options: free messages when done
In reply to Martin ÅgrenHi Martin,
Quoted 8 lines · Martin Ågren
Quoted 7 lines · Elijah Newren
Quoted 5 lines · Martin Ågren
As you noted elsewhere [1], Ben is also working in this area. I'd be perfectly happy to sit on these patches until both of your contributions come through to master.
[1] https://public-inbox.org/git/CABPp-BFh=gL6RnbST2bgtynkij1Z5TMgAr1Via5_VyteF5eBMg@mail.gmail.com/
Quoted 7 lines
Quoted 2 lines
Instead of waiting for these to come through to master, could you just submit based on the top of bp/merge-rename-config?
Sure, here goes. This is based on bp/merge-rename-config, gets rid of all leaks of memory allocated in
setup_unpack_trees_porcelain()and cuts the number of leaks in the test-suite (i.e., the subset of the tests that I run) by around 10%.
Awesome, thanks. I've looked over patches 2 & 3; they look good to me.
Re: [PATCH v2 0/3] unpack_trees_options: free messages when done
Quoted 14 lines · Elijah Newren
Hi Martin,
Quoted 11 lines · Martin Ågren
Quoted 9 lines · Elijah Newren
Quoted 5 lines · Martin Ågren
As you noted elsewhere [1], Ben is also working in this area. I'd be perfectly happy to sit on these patches until both of your contributions come through to master.
[1] https://public-inbox.org/git/CABPp-BFh=gL6RnbST2bgtynkij1Z5TMgAr1Via5_VyteF5eBMg@mail.gmail.com/
Instead of waiting for these to come through to master, could you just submit based on the top of bp/merge-rename-config?
Quoted 7 lines
Quoted 4 lines
Sure, here goes. This is based on bp/merge-rename-config, gets rid of all leaks of memory allocated in
setup_unpack_trees_porcelain()and cuts the number of leaks in the test-suite (i.e., the subset of the tests that I run) by around 10%.Awesome, thanks. I've looked over patches 2 & 3; they look good to me.
I like the symmetry of the naming and locality of the functions. Should help people remember to keep the xstrfmt() and associated free() in sync. Patches look good to me as well.
Re: [PATCH v8 06/16] sequencer: introduce the `merge` command
In reply to Martin ÅgrenHi Martin,
Quoted 10 lines · Martin Ågren
Quoted 6 lines · Phillip Wood
I'm fine with leaving it, I've might get round to doing a small series to clean things up slightly in a few weeks. At the moment
setup_unpack_trees_porcelain()leaks memory as it is called for each merge and allocates new strings each time. It would also be nice if the error messages reflected the command, so it said 'cherry-pick', 'revert' or 'reset' rather than 'merge'This is a small patch series to introduce and use
clear_unpack_trees_porcelain().
Great. Now I have no excuse but must change the sequencer code to output "reset" instead of "merge" ;-)
Seriously speaking again: thank you for those patches. This is truly exciting! I mean, we all touch the same code and move it forward, and somehow it all works out.
Ciao,
Dscho
Re: [PATCH v8 06/16] sequencer: introduce the `merge` command
In reply to Johannes SchindelinFrom: "Johannes Schindelin" <[email protected]>
Quoted 6 lines
This patch is part of the effort to reimplement
--preserve-mergeswith a substantially improved design, a design that has been developed in the Git for Windows project to maintain the dozens of Windows-specific patch series on top of upstream Git.The previous patch implemented the
labelandresetcommands to label
The previous patch was [Patch 05/16] git-rebase--interactive: clarify arguments, so this statement doesn't appear to be true. Has a patch been missed or re-ordered? Or should it be simply "This patch implements" ? Likewise the patch subject would be updated.
Quoted 1 line
commits and to reset to labeled commits. This patch adds the
merge
s/adds/also adds/ ?
Quoted 11 lines
command, with the following syntax:
merge [-C <commit>] <rev> # <oneline>
The <commit> parameter in this instance is the *original* merge commit, whose author and message will be used for the merge commit that is about to be created.
The <rev> parameter refers to the (possibly rewritten) revision to merge. Let's see an example of a todo list:
The example ought to also note that label onto is to# label current HEAD with a name, seeing as this is the first occurance. It may be obvious in retrospect, but not at first reading.
Quoted 4 lines
label onto
# Branch abc
reset onto
Is this reset strictly necessary. We are already there @head.
Quoted 589 lines
pick deadbeef Hello, world!
label abcreset onto
pick cafecafe And now for something completely different merge -C baaabaaa abc # Merge the branch 'abc' into masterTo edit the merge commit's message (a "reword" for merges, if you will), use
-c(lower-case) instead of-C; this convention was borrowed fromgit committhat also supports-cand-Cwith similar meanings.To create *new* merges, i.e. without copying the commit message from an existing commit, simply omit the
-C <commit>parameter (which will open an editor for the merge message):merge abc
This comes in handy when splitting a branch into two or more branches.
Note: this patch only adds support for recursive merges, to keep things simple. Support for octopus merges will be added later in a separate patch series, support for merges using strategies other than the recursive merge is left for the future.
Signed-off-by Johannes Schindelin <[email protected]>---
git-rebase--interactive.sh| 6 +sequencer.c| 407 ++++++++++++++++++++++++++++++++++++-2 files changed, 406 insertions(+), 7 deletions(-)git-rebase--interactive.sh +0
-0@@ -162,6 +162,12 @@ s, squash <commit> = use commit, but meld intoprevious commit
f, fixup <commit> = like \"squash\", but discard this commit's log message x, exec <commit> = run command (the rest of the line) using shell d, drop <commit> = remove commitgit-rebase--interactive.sh +6
-0+l, label <label> = label current HEAD with a name +t, reset <label> = reset HEAD to a label +m, merge [-C <commit> | -c <commit>] <label> [# <oneline>] +. create a merge commit using the original merge commit's +. message (or the oneline, if no original merge commit was +. specified). Use -c <commit> to reword the commit message.These lines can be re-ordered; they are executed from top to bottom. " | git stripspace --comment-lines >>"$todo"
sequencer.c +5
-0@@ -23,6 +23,8 @@#include "hashmap.h" #include "notes-utils.h" #include "sigchain.h" +#include "unpack-trees.h" +#include "worktree.h" #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"@@ -120,6 +122,13 @@ static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha") static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list") static GIT_PATH_FUNC(rebase_path_rewritten_pending, "rebase-merge/rewritten-pending") + +/* +* The path of the file listing refs that need to be deleted after the rebase
+ * finishes. This is used by thelabelcommand to record the need for cleanup.
+ */
+staticGIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
+
/*
* The following files are written by git-rebase just after parsing the
* command-line (and are only consumed, not modified, by the sequencer).sequencer.c +20
-4@@ -244,18 +253,34 @@ static const char *gpg_sign_opt_quoted(struct replay_opts *opts)int sequencer_remove_state (struct replay_opts *opts) { -struct strbuf dir =STRBUF_INIT ; +struct strbuf buf =STRBUF_INIT ;int i; +if (is_rebase_i (opts) && +strbuf_read_file (&buf,rebase_path_refs_to_delete (),0 ) >0 ) { +char *p = buf.buf; +while (*p) { +char *eol =strchr (p,'\n' ); +if (eol) + *eol ='\0' ; +if (delete_ref ("(rebase -i) cleanup" , p,NULL ,0 ) <0 ) +warning (_ ("could not delete '%s'" ), p); +if (!eol) +break ; + p = eol +1 ; + } + } +free (opts->gpg_sign);free (opts->strategy);for (i =0 ; i < opts->xopts_nr; i++)free (opts->xopts[i]);free (opts->xopts); -strbuf_addstr (&dir,get_dir (opts)); -remove_dir_recursively (&dir,0 ); -strbuf_release (&dir); +strbuf_reset (&buf); +strbuf_addstr (&buf,get_dir (opts)); +remove_dir_recursively (&buf,0 ); +strbuf_release (&buf);return 0 ;}
sequencer.c +11
-0@@ -1279,6 +1304,9 @@ enum todo_command {TODO_SQUASH ,/* commands that do something else than handling a single commit */ TODO_EXEC , +TODO_LABEL , +TODO_RESET , +TODO_MERGE ,/* commands that do nothing but are counted for reporting progress */ TODO_NOOP , TODO_DROP,@@ -1297,6 +1325,9 @@ static struct { { 'f', "fixup" }, { 's', "squash" }, { 'x', "exec" }, + { 'l', "label" }, + { 't', "reset" }, + { 'm', "merge" }, { 0, "noop" }, { 'd', "drop" }, { 0, NULL }@@ -1724,9 +1755,14 @@ static int read_and_refresh_cache(struct replay_opts *opts)return 0 ; } +enum todo_item_flags { +TODO_EDIT_MERGE_MSG =1 +}; +struct todo_item {enum todo_command command;struct commit *commit; +unsigned int flags;const char *arg;int arg_len;
size_toffset_in_buf;sequencer.c +19
-1@@ -1761,6 +1797,8 @@ static int parse_insn_line(struct todo_item *item, const char *bol, char *eol) char *end_of_object_name;int i, saved, status, padding; + item->flags =0 ; +/* left-trim */ bol +=strspn (bol," \t" );@@ -1802,13 +1840,29 @@ static int parse_insn_line(struct todo_item *item, const char *bol, char *eol) return error(_("missing arguments for %s"), command_to_string(item->command)); -if (item->command ==TODO_EXEC ) { +if (item->command ==TODO_EXEC || item->command ==TODO_LABEL || + item->command ==TODO_RESET ) { item->commit =NULL ; item->arg = bol; item->arg_len = (int )(eol - bol);return 0 ; } +if (item->command ==TODO_MERGE ) { +if (skip_prefix (bol,"-C" , &bol)) + bol +=strspn (bol," \t" ); +else if (skip_prefix (bol,"-c" , &bol)) { + bol +=strspn (bol," \t" ); + item->flags |=TODO_EDIT_MERGE_MSG ; + }else { + item->flags |=TODO_EDIT_MERGE_MSG ; + item->commit =NULL ; + item->arg = bol; + item->arg_len = (int )(eol - bol); +return 0 ; + } + } + end_of_object_name = (char *) bol +strcspn (bol," \t\n" ); saved = *end_of_object_name;
*end_of_object_name= '\0';sequencer.c +299
-0@@ -2465,6 +2519,305 @@ static int do_exec(const char *command_line)return status; } +static int safe_append (const char *filename,const char *fmt, ...) +{ +va_list ap; +struct lock_file lock =LOCK_INIT ; +int fd =hold_lock_file_for_update (&lock, filename, +LOCK_REPORT_ON_ERROR ); +struct strbuf buf =STRBUF_INIT ; + +if (fd <0 ) +return -1 ; + +if (strbuf_read_file (&buf, filename,0 ) <0 && errno !=ENOENT ) { +error_errno (_ ("could not read '%s'" ), filename); +rollback_lock_file (&lock); +return -1 ; + } +strbuf_complete (&buf,'\n' ); +va_start (ap, fmt); +strbuf_vaddf (&buf, fmt, ap); +va_end (ap); + +if (write_in_full (fd, buf.buf, buf.len) <0 ) { +error_errno (_ ("could not write to '%s'" ), filename); +strbuf_release (&buf); +rollback_lock_file (&lock); +return -1 ; + } +if (commit_lock_file (&lock) <0 ) { +strbuf_release (&buf); +rollback_lock_file (&lock); +return error (_ ("failed to finalize '%s'" ), filename); + } + +strbuf_release (&buf); +return 0 ; +} + +static int do_label (const char *name,int len) +{ +struct ref_store *refs =get_main_ref_store (); +struct ref_transaction *transaction; +struct strbuf ref_name =STRBUF_INIT , err =STRBUF_INIT ; +struct strbuf msg =STRBUF_INIT ; +int ret =0 ; +struct object_id head_oid; + +if (len ==1 && *name =='#' ) +return error ("Illegal label name: '%.*s'" , len, name); + +strbuf_addf (&ref_name,"refs/rewritten/%.*s" , len, name); +strbuf_addf (&msg,"rebase -i (label) '%.*s'" , len, name); + + transaction =ref_store_transaction_begin (refs, &err); +if (!transaction) { +error ("%s" , err.buf); + ret =-1 ; + }else if (get_oid ("HEAD" , &head_oid)) { +error (_ ("could not read HEAD" )); + ret =-1 ; + }else if (ref_transaction_update (transaction, ref_name.buf, &head_oid, +NULL ,0 , msg.buf, &err) <0 || +ref_transaction_commit (transaction, &err)) { +error ("%s" , err.buf); + ret =-1 ; + } +ref_transaction_free (transaction); +strbuf_release (&err); +strbuf_release (&msg); + +if (!ret) + ret =safe_append (rebase_path_refs_to_delete (), +"%s\n" , ref_name.buf); +strbuf_release (&ref_name); + +return ret; +} + +static const char *reflog_message (struct replay_opts *opts, +const char *sub_action,const char *fmt, ...); + +static int do_reset (const char *name,int len,struct replay_opts *opts) +{ +struct strbuf ref_name =STRBUF_INIT ; +struct object_id oid; +struct lock_file lock =LOCK_INIT ; +struct tree_desc desc; +struct tree *tree; +struct unpack_trees_options unpack_tree_opts; +int ret =0 , i; + +if (hold_locked_index (&lock,LOCK_REPORT_ON_ERROR ) <0 ) +return -1 ; + +/* Determine the length of the label */ +for (i =0 ; i < len; i++) +if (isspace (name[i])) + len = i; + +strbuf_addf (&ref_name,"refs/rewritten/%.*s" , len, name); +if (get_oid (ref_name.buf, &oid) && +get_oid (ref_name.buf +strlen ("refs/rewritten/" ), &oid)) { +error (_ ("could not read '%s'" ), ref_name.buf); +rollback_lock_file (&lock); +strbuf_release (&ref_name); +return -1 ; + } + +memset (&unpack_tree_opts,0 ,sizeof (unpack_tree_opts)); + unpack_tree_opts.head_idx =1 ; + unpack_tree_opts.src_index = &the_index; + unpack_tree_opts.dst_index = &the_index; + unpack_tree_opts.fn = oneway_merge; + unpack_tree_opts.merge =1 ; + unpack_tree_opts.update =1 ; + +if (read_cache_unmerged ()) { +rollback_lock_file (&lock); +strbuf_release (&ref_name); +return error_resolve_conflict (_ (action_name (opts))); + } + +if (!fill_tree_descriptor (&desc, &oid)) { +error (_ ("failed to find tree of %s" ),oid_to_hex (&oid)); +rollback_lock_file (&lock); +free ((void *)desc.buffer); +strbuf_release (&ref_name); +return -1 ; + } + +if (unpack_trees (1 , &desc, &unpack_tree_opts)) { +rollback_lock_file (&lock); +free ((void *)desc.buffer); +strbuf_release (&ref_name); +return -1 ; + } + + tree =parse_tree_indirect (&oid); +prime_cache_tree (&the_index, tree); + +if (write_locked_index (&the_index, &lock,COMMIT_LOCK ) <0 ) + ret =error (_ ("could not write index" )); +free ((void *)desc.buffer); + +if (!ret) + ret =update_ref (reflog_message (opts,"reset" ,"'%.*s'" , + len, name),"HEAD" , &oid, +NULL ,0 ,UPDATE_REFS_MSG_ON_ERR ); + +strbuf_release (&ref_name); +return ret; +} + +static int do_merge (struct commit *commit,const char *arg,int arg_len, +int flags,struct replay_opts *opts) +{ +int run_commit_flags = (flags &TODO_EDIT_MERGE_MSG ) ? +EDIT_MSG |VERIFY_MSG :0 ; +struct strbuf ref_name =STRBUF_INIT ; +struct commit *head_commit, *merge_commit, *i; +struct commit_list *bases, *j, *reversed =NULL ; +struct merge_options o; +int merge_arg_len, oneline_offset, ret; +static struct lock_file lock; +const char *p; + +if (hold_locked_index (&lock,LOCK_REPORT_ON_ERROR ) <0 ) { + ret =-1 ; + goto leave_merge; + } + + head_commit =lookup_commit_reference_by_name ("HEAD" ); +if (!head_commit) { + ret =error (_ ("cannot merge without a current revision" )); + goto leave_merge; + } + + oneline_offset = arg_len; + merge_arg_len =strcspn (arg," \t\n" ); + p = arg + merge_arg_len; + p +=strspn (p," \t\n" ); +if (*p =='#' && (!p[1 ] ||isspace (p[1 ]))) { + p +=1 +strspn (p +1 ," \t\n" ); + oneline_offset = p - arg; + }else if (p - arg < arg_len) +BUG ("octopus merges are not supported yet: '%s'" , p); + +strbuf_addf (&ref_name,"refs/rewritten/%.*s" , merge_arg_len, arg); + merge_commit =lookup_commit_reference_by_name (ref_name.buf); +if (!merge_commit) { +/* fall back to non-rewritten ref or commit */ +strbuf_splice (&ref_name,0 ,strlen ("refs/rewritten/" ),"" ,0 ); + merge_commit =lookup_commit_reference_by_name (ref_name.buf); + } + +if (!merge_commit) { + ret =error (_ ("could not resolve '%s'" ), ref_name.buf); + goto leave_merge; + } + +if (commit) { +const char *message =get_commit_buffer (commit,NULL ); +const char *body; +int len; + +if (!message) { + ret =error (_ ("could not get commit message of '%s'" ), +oid_to_hex (&commit->object.oid)); + goto leave_merge; + } +write_author_script (message); +find_commit_subject (message, &body); + len =strlen (body); + ret =write_message (body, len,git_path_merge_msg (),0 ); +unuse_commit_buffer (commit, message); +if (ret) { +error_errno (_ ("could not write '%s'" ), +git_path_merge_msg ()); + goto leave_merge; + } + }else { +struct strbuf buf =STRBUF_INIT ; +int len; + +strbuf_addf (&buf,"author %s" ,git_author_info (0 )); +write_author_script (buf.buf); +strbuf_reset (&buf); + +if (oneline_offset < arg_len) { + p = arg + oneline_offset; + len = arg_len - oneline_offset; + }else { +strbuf_addf (&buf,"Merge branch '%.*s'" , + merge_arg_len, arg); + p = buf.buf; + len = buf.len; + } + + ret =write_message (p, len,git_path_merge_msg (),0 ); +strbuf_release (&buf); +if (ret) { +error_errno (_ ("could not write '%s'" ), +git_path_merge_msg ()); + goto leave_merge; + } + } + +write_message (oid_to_hex (&merge_commit->object.oid),GIT_SHA1_HEXSZ , +git_path_merge_head (),0 ); +write_message ("no-ff" ,5 ,git_path_merge_mode (),0 ); + + bases =get_merge_bases (head_commit, merge_commit); +for (j = bases; j; j = j->next) +commit_list_insert (j->item, &reversed); +free_commit_list (bases); + +read_cache (); +init_merge_options (&o); + o.branch1 ="HEAD" ; + o.branch2 = ref_name.buf; + o.buffer_output =2 ; + + ret =merge_recursive (&o, head_commit, merge_commit, reversed, &i); +if (ret <=0 ) +fputs (o.obuf.buf, stdout); +strbuf_release (&o.obuf); +if (ret <0 ) { +error (_ ("could not even attempt to merge '%.*s'" ), + merge_arg_len, arg); + goto leave_merge; + } +/* +* The return value of merge_recursive() is 1 on clean, and 0 on +* unclean merge. +* +* Let's reverse that, so that do_merge() returns 0 upon success and +* 1 upon failed merge (keeping the return value -1 for the cases where +* we will want to reschedule the `merge` command). +*/ + ret = !ret; + +if (active_cache_changed && +write_locked_index (&the_index, &lock,COMMIT_LOCK )) { + ret =error (_ ("merge: Unable to write new index file" )); + goto leave_merge; + } + +rollback_lock_file (&lock); +if (ret) +rerere (opts->allow_rerere_auto); +else + ret =run_git_commit (git_path_merge_msg (), opts, + run_commit_flags); + +leave_merge: +strbuf_release (&ref_name); +rollback_lock_file (&lock); +return ret; +} +static int is_final_fixup (struct todo_list *todo_list) {int i = todo_list->current;@@ -2568,7 +2921,7 @@ N_("Could not execute the todo command\n"static int
pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
{
- int res = 0;
+ int res = 0, reschedule = 0;
setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
if (opts->allow_ff)sequencer.c +1
-1@@ -2639,7 +2992,7 @@ static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)intend_to_amend ();return error_failed_squash (item->commit, opts, item->arg_len, item->arg); - }else if (res &&is_rebase_i (opts)) + }else if (res &&is_rebase_i (opts) && item->commit) return res | error_with_patch(item->commit, item->arg, item->arg_len, opts, res,
item->command==TODO_REWORD);sequencer.c +32
-0@@ -2665,9 +3018,41 @@ static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)/* `current` will be incremented below */ todo_list->current =-1 ; } + }else if (item->command ==TODO_LABEL ) { +if ((res =do_label (item->arg, item->arg_len))) + reschedule =1 ; + }else if (item->command ==TODO_RESET ) { +if ((res =do_reset (item->arg, item->arg_len, opts))) + reschedule =1 ; + }else if (item->command ==TODO_MERGE ) { +if ((res =do_merge (item->commit, + item->arg, item->arg_len, + item->flags, opts)) <0 ) + reschedule =1 ; +else if (res >0 ) +/* failed with merge conflicts */ +return error_with_patch (item->commit, + item->arg, + item->arg_len, opts, + res,0 ); }else if (!is_noop (item->command))return error (_ ("unknown command %d" ), item->command); +if (reschedule) { +advise (_ (rescheduled_advice), +get_item_line_length (todo_list, + todo_list->current), +get_item_line (todo_list, todo_list->current)); + todo_list->current--; +if (save_todo (todo_list, opts)) +return -1 ; +if (item->commit) +return error_with_patch (item->commit, + item->arg, + item->arg_len, opts, + res,0 ); + } + todo_list->current++;if (res)return res;
sequencer.c +8
-0@@ -3147,8 +3532,16 @@ int transform_todos(unsigned flags) short_commit_name(item->commit) :oid_to_hex (&item->commit->object.oid); +if (item->command ==TODO_MERGE ) { +if (item->flags &TODO_EDIT_MERGE_MSG ) +strbuf_addstr (&buf," -c" ); +else +strbuf_addstr (&buf," -C" ); + } +strbuf_addf (&buf," %s" , oid); } +/* add all the rest */ if (!item->arg_len)strbuf_addch (&buf,'\n' );Signature · 1 line
2.17.0.windows.1.15.gaa56ade3205
Re: [PATCH v8 06/16] sequencer: introduce the `merge` command
Hi Philip,
Quoted 6 lines · Philip Oakley
From: "Johannes Schindelin" <[email protected]>
Quoted 5 lines
This patch is part of the effort to reimplement
--preserve-mergeswith a substantially improved design, a design that has been developed in the Git for Windows project to maintain the dozens of Windows-specific patch series on top of upstream Git.
Quoted 6 lines
Quoted 1 line
The previous patch implemented the
labelandresetcommands to labelThe previous patch was [Patch 05/16] git-rebase--interactive: clarify arguments, so this statement doesn't appear to be true. Has a patch been missed or re-ordered? Or should it be simply "This patch implements" ? Likewise the patch subject would be updated.
As Phillip guessed correctly, it was a mistaken git commit --amend.
Quoted 3 lines
Quoted 1 line
commits and to reset to labeled commits. This patch adds the
merges/adds/also adds/ ?
No, as I really want to keep those two commits separate. I disentangled them.
Quoted 8 lines
Quoted 8 lines
command, with the following syntax:
merge [-C <commit>] <rev> # <oneline>
The <commit> parameter in this instance is the *original* merge commit, whose author and message will be used for the merge commit that is about to be created.
Quoted 6 lines
Quoted 3 lines
The <rev> parameter refers to the (possibly rewritten) revision to merge. Let's see an example of a todo list:
The example ought to also note that
label ontois to# label current HEAD with a name, seeing as this is the first occurance. It may be obvious in retrospect, but not at first reading.
I added some sentence to describe what label onto does and why.
Quoted 6 lines
Quoted 4 lines
label onto
# Branch abc
reset ontoIs this reset strictly necessary. We are already there @head.
No, this is not strictly necessary, but
- it makes it easier to auto-generate (otherwise you would have to keep track of the "current HEAD" while generating that todo list, and
- if I keep the reset onto there, then it is *a lot* easier to reorder topic branches.
Ciao,
Dscho
Re: [PATCH v8 06/16] sequencer: introduce the `merge` command
From: "Johannes Schindelin" <[email protected]> : Monday, April 23, 2018 1:03 PM
Subject: Re: [PATCH v8 06/16] sequencer: introduce the merge command
Quoted 2 lines
Hi Philip,
[...]
Quoted 9 lines
Quoted 7 lines
Quoted 5 lines
label onto
# Branch abc
reset ontoIs this reset strictly necessary. We are already there @head.
No, this is not strictly necessary, but
I've realised my misunderstanding. I was thinking this (and others) was equivalent to
$ git reset <thatHead'onto'> # maybe even --hard,
i.e. affecting the worktree
rather that just being a movement of the Head rev (though I may be having brain fade here regarding untracked files etc..)
Quoted 10 lines
- it makes it easier to auto-generate (otherwise you would have to keep track of the "current HEAD" while generating that todo list, and
- if I keep the
reset ontothere, then it is *a lot* easier to reorder topic branches.Ciao,
Dscho
Thanks
Philip
Re: [PATCH v8 06/16] sequencer: introduce the `merge` command
Hi Philip,
Quoted 13 lines · Philip Oakley
From: "Johannes Schindelin" <[email protected]> : Monday, April 23, 2018 1:03 PM
Subject: Re: [PATCH v8 06/16] sequencer: introduce themergecommand[...]
Quoted 8 lines
Quoted 7 lines
Quoted 5 lines
label onto
# Branch abc
reset ontoIs this reset strictly necessary. We are already there @head.
Quoted 8 lines
Quoted 1 line
No, this is not strictly necessary, but
I've realised my misunderstanding. I was thinking this (and others) was equivalent to
$ git reset <thatHead'onto'> # maybe even --hard,i.e. affecting the worktree
Oh, but it *is* affecting the worktree. In this case, since we label HEAD and then immediately reset to the label, there is just nothing to change.
Consider this example, though:
label onto # Branch: from-philip reset onto pick abcdef something label from-philip # Branch: with-love reset onto pick 012345 else label with-love reset onto merge -C 98765 from-philip merge -C 43210 with-love
Only in the first instance is the reset onto a no-op, an incidental one. After picking something and labeling the result as from-philip, though, the next reset onto really resets the worktree.
Quoted 2 lines
rather that just being a movement of the Head rev (though I may be having brain fade here regarding untracked files etc..)
The current way of doing things does not allow the reset to overwrite untracked, nor ignored files (I think, I only verified the former, not the latter).
But yeah, it is not just a movement of HEAD. It does reset the worktree, although quite a bit more gently (and safely) than git reset --hard. In that respect, this patch series is a drastic improvement over the Git garden shears (which is the shell script I use in Git for Windows which inspired this here patch series).
Ciao,
Dscho
Re: [PATCH v8 06/16] sequencer: introduce the `merge` command
From: "Johannes Schindelin" <[email protected]>
Quoted 56 lines · Philip Oakley
Quoted 14 lines
From: "Johannes Schindelin" <[email protected]> : Monday, April 23, 2018 1:03 PM
Subject: Re: [PATCH v8 06/16] sequencer: introduce themergecommand[...]
Quoted 8 lines
Quoted 7 lines
Quoted 5 lines
label onto
# Branch abc
reset ontoIs this reset strictly necessary. We are already there @head.
Quoted 8 lines
Quoted 1 line
No, this is not strictly necessary, but
I've realised my misunderstanding. I was thinking this (and others) was equivalent to
$ git reset <thatHead'onto'> # maybe even --hard,i.e. affecting the worktree
Oh, but it *is* affecting the worktree. In this case, since we label HEAD and then immediately reset to the label, there is just nothing to change.
Consider this example, though:
label onto
# Branch: from-philip
reset onto
pick abcdef something
label from-philip# Branch: with-love
reset onto
pick 012345 else
label with-lovereset onto
merge -C 98765 from-philip
merge -C 43210 with-loveOnly in the first instance is the
reset ontoa no-op, an incidental one. After pickingsomethingand labeling the result asfrom-philip, though, the nextreset ontoreally resets the worktree.Quoted 2 lines
rather that just being a movement of the Head rev (though I may be having brain fade here regarding untracked files etc..)
The current way of doing things does not allow the
resetto overwrite untracked, nor ignored files (I think, I only verified the former, not the latter).
Quoted 6 lines
But yeah, it is not just a movement of HEAD. It does reset the worktree, although quite a bit more gently (and safely) than
git reset --hard. In that respect, this patch series is a drastic improvement over the Git garden shears (which is the shell script I use in Git for Windows which inspired this here patch series).
thanks for clarifying. Yes my reasoning was a total brain fade ... Along with the fact that it's a soft/safe/gentle reset. --
Philip
Re: [PATCH v8 06/16] sequencer: introduce the `merge` command
In reply to Johannes SchindelinFrom: "Johannes Schindelin" <[email protected]>
Quoted 6 lines
This patch is part of the effort to reimplement
--preserve-mergeswith a substantially improved design, a design that has been developed in the Git for Windows project to maintain the dozens of Windows-specific patch series on top of upstream Git.The previous patch implemented the
labelandresetcommands to label
The previous patch was [Patch 05/16] git-rebase--interactive: clarify arguments, so this statement doesn't appear to be true. Has a patch been missed or re-ordered? Or should it be simply "This patch implements" ? Likewise the patch subject would be updated.
Quoted 1 line
commits and to reset to labeled commits. This patch adds the
merge
s/adds/also adds/ ?
Quoted 11 lines
command, with the following syntax:
merge [-C <commit>] <rev> # <oneline>
The <commit> parameter in this instance is the *original* merge commit, whose author and message will be used for the merge commit that is about to be created.
The <rev> parameter refers to the (possibly rewritten) revision to merge. Let's see an example of a todo list:
The example ought to also note that label onto is to# label current HEAD with a name, seeing as this is the first occurance. It may be obvious in retrospect, but not at first reading.
Quoted 4 lines
label onto
# Branch abc
reset onto
Is this reset strictly necessary. We are already there @head.
Quoted 587 lines
pick deadbeef Hello, world!
label abcreset onto
pick cafecafe And now for something completely different merge -C baaabaaa abc # Merge the branch 'abc' into masterTo edit the merge commit's message (a "reword" for merges, if you will), use
-c(lower-case) instead of-C; this convention was borrowed fromgit committhat also supports-cand-Cwith similar meanings.To create *new* merges, i.e. without copying the commit message from an existing commit, simply omit the
-C <commit>parameter (which will open an editor for the merge message):merge abc
This comes in handy when splitting a branch into two or more branches.
Note: this patch only adds support for recursive merges, to keep things simple. Support for octopus merges will be added later in a separate patch series, support for merges using strategies other than the recursive merge is left for the future.
Signed-off-by Johannes Schindelin <[email protected]>---
git-rebase--interactive.sh| 6 +sequencer.c| 407 ++++++++++++++++++++++++++++++++++++-2 files changed, 406 insertions(+), 7 deletions(-)git-rebase--interactive.sh +0
-0@@ -162,6 +162,12 @@ s, squash <commit> = use commit, but meld intoprevious commit
f, fixup <commit> = like \"squash\", but discard this commit's log message x, exec <commit> = run command (the rest of the line) using shell d, drop <commit> = remove commitgit-rebase--interactive.sh +6
-0+l, label <label> = label current HEAD with a name +t, reset <label> = reset HEAD to a label +m, merge [-C <commit> | -c <commit>] <label> [# <oneline>] +. create a merge commit using the original merge commit's +. message (or the oneline, if no original merge commit was +. specified). Use -c <commit> to reword the commit message.These lines can be re-ordered; they are executed from top to bottom. " | git stripspace --comment-lines >>"$todo"
sequencer.c +5
-0@@ -23,6 +23,8 @@#include "hashmap.h" #include "notes-utils.h" #include "sigchain.h" +#include "unpack-trees.h" +#include "worktree.h" #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"@@ -120,6 +122,13 @@ static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha") static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list") static GIT_PATH_FUNC(rebase_path_rewritten_pending, "rebase-merge/rewritten-pending") + +/* +* The path of the file listing refs that need to be deleted after the rebase
+ * finishes. This is used by thelabelcommand to record the need for cleanup.
+ */
+staticGIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
+
/*
* The following files are written by git-rebase just after parsing the
* command-line (and are only consumed, not modified, by the sequencer).sequencer.c +20
-4@@ -244,18 +253,34 @@ static const char *gpg_sign_opt_quoted(struct replay_opts *opts)int sequencer_remove_state (struct replay_opts *opts) { -struct strbuf dir =STRBUF_INIT ; +struct strbuf buf =STRBUF_INIT ;int i; +if (is_rebase_i (opts) && +strbuf_read_file (&buf,rebase_path_refs_to_delete (),0 ) >0 ) { +char *p = buf.buf; +while (*p) { +char *eol =strchr (p,'\n' ); +if (eol) + *eol ='\0' ; +if (delete_ref ("(rebase -i) cleanup" , p,NULL ,0 ) <0 ) +warning (_ ("could not delete '%s'" ), p); +if (!eol) +break ; + p = eol +1 ; + } + } +free (opts->gpg_sign);free (opts->strategy);for (i =0 ; i < opts->xopts_nr; i++)free (opts->xopts[i]);free (opts->xopts); -strbuf_addstr (&dir,get_dir (opts)); -remove_dir_recursively (&dir,0 ); -strbuf_release (&dir); +strbuf_reset (&buf); +strbuf_addstr (&buf,get_dir (opts)); +remove_dir_recursively (&buf,0 ); +strbuf_release (&buf);return 0 ;}
sequencer.c +11
-0@@ -1279,6 +1304,9 @@ enum todo_command {TODO_SQUASH ,/* commands that do something else than handling a single commit */ TODO_EXEC , +TODO_LABEL , +TODO_RESET , +TODO_MERGE ,/* commands that do nothing but are counted for reporting progress */ TODO_NOOP , TODO_DROP,@@ -1297,6 +1325,9 @@ static struct { { 'f', "fixup" }, { 's', "squash" }, { 'x', "exec" }, + { 'l', "label" }, + { 't', "reset" }, + { 'm', "merge" }, { 0, "noop" }, { 'd', "drop" }, { 0, NULL }@@ -1724,9 +1755,14 @@ static int read_and_refresh_cache(struct replay_opts *opts)return 0 ; } +enum todo_item_flags { +TODO_EDIT_MERGE_MSG =1 +}; +struct todo_item {enum todo_command command;struct commit *commit; +unsigned int flags;const char *arg;int arg_len;
size_toffset_in_buf;sequencer.c +19
-1@@ -1761,6 +1797,8 @@ static int parse_insn_line(struct todo_item *item, const char *bol, char *eol) char *end_of_object_name;int i, saved, status, padding; + item->flags =0 ; +/* left-trim */ bol +=strspn (bol," \t" );@@ -1802,13 +1840,29 @@ static int parse_insn_line(struct todo_item *item, const char *bol, char *eol) return error(_("missing arguments for %s"), command_to_string(item->command)); -if (item->command ==TODO_EXEC ) { +if (item->command ==TODO_EXEC || item->command ==TODO_LABEL || + item->command ==TODO_RESET ) { item->commit =NULL ; item->arg = bol; item->arg_len = (int )(eol - bol);return 0 ; } +if (item->command ==TODO_MERGE ) { +if (skip_prefix (bol,"-C" , &bol)) + bol +=strspn (bol," \t" ); +else if (skip_prefix (bol,"-c" , &bol)) { + bol +=strspn (bol," \t" ); + item->flags |=TODO_EDIT_MERGE_MSG ; + }else { + item->flags |=TODO_EDIT_MERGE_MSG ; + item->commit =NULL ; + item->arg = bol; + item->arg_len = (int )(eol - bol); +return 0 ; + } + } + end_of_object_name = (char *) bol +strcspn (bol," \t\n" ); saved = *end_of_object_name;
*end_of_object_name= '\0';sequencer.c +301
-2@@ -2465,6 +2519,305 @@ static int do_exec(const char *command_line)return status; } +static int safe_append (const char *filename,const char *fmt, ...) +{ +va_list ap; +struct lock_file lock =LOCK_INIT ; +int fd =hold_lock_file_for_update (&lock, filename, +LOCK_REPORT_ON_ERROR ); +struct strbuf buf =STRBUF_INIT ; + +if (fd <0 ) +return -1 ; + +if (strbuf_read_file (&buf, filename,0 ) <0 && errno !=ENOENT ) { +error_errno (_ ("could not read '%s'" ), filename); +rollback_lock_file (&lock); +return -1 ; + } +strbuf_complete (&buf,'\n' ); +va_start (ap, fmt); +strbuf_vaddf (&buf, fmt, ap); +va_end (ap); + +if (write_in_full (fd, buf.buf, buf.len) <0 ) { +error_errno (_ ("could not write to '%s'" ), filename); +strbuf_release (&buf); +rollback_lock_file (&lock); +return -1 ; + } +if (commit_lock_file (&lock) <0 ) { +strbuf_release (&buf); +rollback_lock_file (&lock); +return error (_ ("failed to finalize '%s'" ), filename); + } + +strbuf_release (&buf); +return 0 ; +} + +static int do_label (const char *name,int len) +{ +struct ref_store *refs =get_main_ref_store (); +struct ref_transaction *transaction; +struct strbuf ref_name =STRBUF_INIT , err =STRBUF_INIT ; +struct strbuf msg =STRBUF_INIT ; +int ret =0 ; +struct object_id head_oid; + +if (len ==1 && *name =='#' ) +return error ("Illegal label name: '%.*s'" , len, name); + +strbuf_addf (&ref_name,"refs/rewritten/%.*s" , len, name); +strbuf_addf (&msg,"rebase -i (label) '%.*s'" , len, name); + + transaction =ref_store_transaction_begin (refs, &err); +if (!transaction) { +error ("%s" , err.buf); + ret =-1 ; + }else if (get_oid ("HEAD" , &head_oid)) { +error (_ ("could not read HEAD" )); + ret =-1 ; + }else if (ref_transaction_update (transaction, ref_name.buf, &head_oid, +NULL ,0 , msg.buf, &err) <0 || +ref_transaction_commit (transaction, &err)) { +error ("%s" , err.buf); + ret =-1 ; + } +ref_transaction_free (transaction); +strbuf_release (&err); +strbuf_release (&msg); + +if (!ret) + ret =safe_append (rebase_path_refs_to_delete (), +"%s\n" , ref_name.buf); +strbuf_release (&ref_name); + +return ret; +} + +static const char *reflog_message (struct replay_opts *opts, +const char *sub_action,const char *fmt, ...); + +static int do_reset (const char *name,int len,struct replay_opts *opts) +{ +struct strbuf ref_name =STRBUF_INIT ; +struct object_id oid; +struct lock_file lock =LOCK_INIT ; +struct tree_desc desc; +struct tree *tree; +struct unpack_trees_options unpack_tree_opts; +int ret =0 , i; + +if (hold_locked_index (&lock,LOCK_REPORT_ON_ERROR ) <0 ) +return -1 ; + +/* Determine the length of the label */ +for (i =0 ; i < len; i++) +if (isspace (name[i])) + len = i; + +strbuf_addf (&ref_name,"refs/rewritten/%.*s" , len, name); +if (get_oid (ref_name.buf, &oid) && +get_oid (ref_name.buf +strlen ("refs/rewritten/" ), &oid)) { +error (_ ("could not read '%s'" ), ref_name.buf); +rollback_lock_file (&lock); +strbuf_release (&ref_name); +return -1 ; + } + +memset (&unpack_tree_opts,0 ,sizeof (unpack_tree_opts)); + unpack_tree_opts.head_idx =1 ; + unpack_tree_opts.src_index = &the_index; + unpack_tree_opts.dst_index = &the_index; + unpack_tree_opts.fn = oneway_merge; + unpack_tree_opts.merge =1 ; + unpack_tree_opts.update =1 ; + +if (read_cache_unmerged ()) { +rollback_lock_file (&lock); +strbuf_release (&ref_name); +return error_resolve_conflict (_ (action_name (opts))); + } + +if (!fill_tree_descriptor (&desc, &oid)) { +error (_ ("failed to find tree of %s" ),oid_to_hex (&oid)); +rollback_lock_file (&lock); +free ((void *)desc.buffer); +strbuf_release (&ref_name); +return -1 ; + } + +if (unpack_trees (1 , &desc, &unpack_tree_opts)) { +rollback_lock_file (&lock); +free ((void *)desc.buffer); +strbuf_release (&ref_name); +return -1 ; + } + + tree =parse_tree_indirect (&oid); +prime_cache_tree (&the_index, tree); + +if (write_locked_index (&the_index, &lock,COMMIT_LOCK ) <0 ) + ret =error (_ ("could not write index" )); +free ((void *)desc.buffer); + +if (!ret) + ret =update_ref (reflog_message (opts,"reset" ,"'%.*s'" , + len, name),"HEAD" , &oid, +NULL ,0 ,UPDATE_REFS_MSG_ON_ERR ); + +strbuf_release (&ref_name); +return ret; +} + +static int do_merge (struct commit *commit,const char *arg,int arg_len, +int flags,struct replay_opts *opts) +{ +int run_commit_flags = (flags &TODO_EDIT_MERGE_MSG ) ? +EDIT_MSG |VERIFY_MSG :0 ; +struct strbuf ref_name =STRBUF_INIT ; +struct commit *head_commit, *merge_commit, *i; +struct commit_list *bases, *j, *reversed =NULL ; +struct merge_options o; +int merge_arg_len, oneline_offset, ret; +static struct lock_file lock; +const char *p; + +if (hold_locked_index (&lock,LOCK_REPORT_ON_ERROR ) <0 ) { + ret =-1 ; + goto leave_merge; + } + + head_commit =lookup_commit_reference_by_name ("HEAD" ); +if (!head_commit) { + ret =error (_ ("cannot merge without a current revision" )); + goto leave_merge; + } + + oneline_offset = arg_len; + merge_arg_len =strcspn (arg," \t\n" ); + p = arg + merge_arg_len; + p +=strspn (p," \t\n" ); +if (*p =='#' && (!p[1 ] ||isspace (p[1 ]))) { + p +=1 +strspn (p +1 ," \t\n" ); + oneline_offset = p - arg; + }else if (p - arg < arg_len) +BUG ("octopus merges are not supported yet: '%s'" , p); + +strbuf_addf (&ref_name,"refs/rewritten/%.*s" , merge_arg_len, arg); + merge_commit =lookup_commit_reference_by_name (ref_name.buf); +if (!merge_commit) { +/* fall back to non-rewritten ref or commit */ +strbuf_splice (&ref_name,0 ,strlen ("refs/rewritten/" ),"" ,0 ); + merge_commit =lookup_commit_reference_by_name (ref_name.buf); + } + +if (!merge_commit) { + ret =error (_ ("could not resolve '%s'" ), ref_name.buf); + goto leave_merge; + } + +if (commit) { +const char *message =get_commit_buffer (commit,NULL ); +const char *body; +int len; + +if (!message) { + ret =error (_ ("could not get commit message of '%s'" ), +oid_to_hex (&commit->object.oid)); + goto leave_merge; + } +write_author_script (message); +find_commit_subject (message, &body); + len =strlen (body); + ret =write_message (body, len,git_path_merge_msg (),0 ); +unuse_commit_buffer (commit, message); +if (ret) { +error_errno (_ ("could not write '%s'" ), +git_path_merge_msg ()); + goto leave_merge; + } + }else { +struct strbuf buf =STRBUF_INIT ; +int len; + +strbuf_addf (&buf,"author %s" ,git_author_info (0 )); +write_author_script (buf.buf); +strbuf_reset (&buf); + +if (oneline_offset < arg_len) { + p = arg + oneline_offset; + len = arg_len - oneline_offset; + }else { +strbuf_addf (&buf,"Merge branch '%.*s'" , + merge_arg_len, arg); + p = buf.buf; + len = buf.len; + } + + ret =write_message (p, len,git_path_merge_msg (),0 ); +strbuf_release (&buf); +if (ret) { +error_errno (_ ("could not write '%s'" ), +git_path_merge_msg ()); + goto leave_merge; + } + } + +write_message (oid_to_hex (&merge_commit->object.oid),GIT_SHA1_HEXSZ , +git_path_merge_head (),0 ); +write_message ("no-ff" ,5 ,git_path_merge_mode (),0 ); + + bases =get_merge_bases (head_commit, merge_commit); +for (j = bases; j; j = j->next) +commit_list_insert (j->item, &reversed); +free_commit_list (bases); + +read_cache (); +init_merge_options (&o); + o.branch1 ="HEAD" ; + o.branch2 = ref_name.buf; + o.buffer_output =2 ; + + ret =merge_recursive (&o, head_commit, merge_commit, reversed, &i); +if (ret <=0 ) +fputs (o.obuf.buf, stdout); +strbuf_release (&o.obuf); +if (ret <0 ) { +error (_ ("could not even attempt to merge '%.*s'" ), + merge_arg_len, arg); + goto leave_merge; + } +/* +* The return value of merge_recursive() is 1 on clean, and 0 on +* unclean merge. +* +* Let's reverse that, so that do_merge() returns 0 upon success and +* 1 upon failed merge (keeping the return value -1 for the cases where +* we will want to reschedule the `merge` command). +*/ + ret = !ret; + +if (active_cache_changed && +write_locked_index (&the_index, &lock,COMMIT_LOCK )) { + ret =error (_ ("merge: Unable to write new index file" )); + goto leave_merge; + } + +rollback_lock_file (&lock); +if (ret) +rerere (opts->allow_rerere_auto); +else + ret =run_git_commit (git_path_merge_msg (), opts, + run_commit_flags); + +leave_merge: +strbuf_release (&ref_name); +rollback_lock_file (&lock); +return ret; +} +static int is_final_fixup (struct todo_list *todo_list) {int i = todo_list->current;@@ -2568,7 +2921,7 @@ N_("Could not execute the todo command\n"static int pick_commits (struct todo_list *todo_list,struct replay_opts *opts) { -int res =0 ; +int res =0 , reschedule =0 ;setenv (GIT_REFLOG_ACTION ,action_name (opts),0 );if (opts->allow_ff)@@ -2639,7 +2992,7 @@ static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)intend_to_amend ();return error_failed_squash (item->commit, opts, item->arg_len, item->arg); - }else if (res &&is_rebase_i (opts)) + }else if (res &&is_rebase_i (opts) && item->commit) return res | error_with_patch(item->commit, item->arg, item->arg_len, opts, res,
item->command==TODO_REWORD);sequencer.c +32
-0@@ -2665,9 +3018,41 @@ static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)/* `current` will be incremented below */ todo_list->current =-1 ; } + }else if (item->command ==TODO_LABEL ) { +if ((res =do_label (item->arg, item->arg_len))) + reschedule =1 ; + }else if (item->command ==TODO_RESET ) { +if ((res =do_reset (item->arg, item->arg_len, opts))) + reschedule =1 ; + }else if (item->command ==TODO_MERGE ) { +if ((res =do_merge (item->commit, + item->arg, item->arg_len, + item->flags, opts)) <0 ) + reschedule =1 ; +else if (res >0 ) +/* failed with merge conflicts */ +return error_with_patch (item->commit, + item->arg, + item->arg_len, opts, + res,0 ); }else if (!is_noop (item->command))return error (_ ("unknown command %d" ), item->command); +if (reschedule) { +advise (_ (rescheduled_advice), +get_item_line_length (todo_list, + todo_list->current), +get_item_line (todo_list, todo_list->current)); + todo_list->current--; +if (save_todo (todo_list, opts)) +return -1 ; +if (item->commit) +return error_with_patch (item->commit, + item->arg, + item->arg_len, opts, + res,0 ); + } + todo_list->current++;if (res)return res;
sequencer.c +8
-0@@ -3147,8 +3532,16 @@ int transform_todos(unsigned flags) short_commit_name(item->commit) :oid_to_hex (&item->commit->object.oid); +if (item->command ==TODO_MERGE ) { +if (item->flags &TODO_EDIT_MERGE_MSG ) +strbuf_addstr (&buf," -c" ); +else +strbuf_addstr (&buf," -C" ); + } +strbuf_addf (&buf," %s" , oid); } +/* add all the rest */ if (!item->arg_len)strbuf_addch (&buf,'\n' );Signature · 1 line
2.17.0.windows.1.15.gaa56ade3205
PATCH v8 7/16 sequencer: fast-forward `merge` commands, if possible
In reply to Johannes SchindelinJust like with regular pick commands, if we are trying to rebase a merge commit, we now test whether the parents of said commit match HEAD and the commits to be merged, and fast-forward if possible.
This is not only faster, but also avoids unnecessary proliferation of new objects.
--- sequencer.c | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-)
sequencer.c +32 -1
@@ -2680,7 +2680,7 @@ static int do_merge(struct commit *commit, const char *arg, int arg_len,struct commit *head_commit, *merge_commit, *i;struct commit_list *bases, *j, *reversed =NULL ;struct merge_options o; -int merge_arg_len, oneline_offset, ret; +int merge_arg_len, oneline_offset, can_fast_forward, ret;static struct lock_file lock;const char *p;
@@ -2765,6 +2765,37 @@ static int do_merge(struct commit *commit, const char *arg, int arg_len, } } +/* +* If HEAD is not identical to the first parent of the original merge +* commit, we cannot fast-forward. +*/ + can_fast_forward = opts->allow_ff && commit && commit->parents && + !oidcmp (&commit->parents->item->object.oid, + &head_commit->object.oid); + +/* +* If the merge head is different from the original one, we cannot +* fast-forward. +*/ +if (can_fast_forward) { +struct commit_list *second_parent = commit->parents->next; + +if (second_parent && !second_parent->next && +oidcmp (&merge_commit->object.oid, + &second_parent->item->object.oid)) + can_fast_forward =0 ; + } + +if (can_fast_forward && commit->parents->next && + !commit->parents->next->next && + !oidcmp (&commit->parents->next->item->object.oid, + &merge_commit->object.oid)) { +rollback_lock_file (&lock); + ret =fast_forward_to (&commit->object.oid, + &head_commit->object.oid,0 , opts); + goto leave_merge; + } +write_message (oid_to_hex (&merge_commit->object.oid),GIT_SHA1_HEXSZ ,git_path_merge_head (),0 );write_message ("no-ff" ,5 ,git_path_merge_mode (),0 );
Signature · 1 line
2.17.0.windows.1.15.gaa56ade3205
PATCH v8 8/16 rebase-helper --make-script: introduce a flag to rebase merges
In reply to Johannes SchindelinThe sequencer just learned new commands intended to recreate branch structure (similar in spirit to --preserve-merges, but with a substantially less-broken design).
Let's allow the rebase--helper to generate todo lists making use of these commands, triggered by the new --rebase-merges option. For a commit topology like this (where the HEAD points to C):
- A - B - C \ / D
the generated todo list would look like this:
# branch D pick 0123 A label branch-point pick 1234 D label D
reset branch-point pick 2345 B merge -C 3456 D # C
To keep things simple, we first only implement support for merge commits with exactly two parents, leaving support for octopus merges to a later patch series.
As a special, hard-coded label, all merge-rebasing todo lists start with the command label onto so that we can later always refer to the revision onto which everything is rebased.
--- builtin/rebase--helper.c | 4 +- sequencer.c | 351 ++++++++++++++++++++++++++++++++++++++- sequencer.h | 1 + 3 files changed, 353 insertions(+), 3 deletions(-)
builtin/rebase--helper.c +3 -1
@@ -12,7 +12,7 @@ static const char * const builtin_rebase_helper_usage[] = {int cmd_rebase__helper (int argc,const char **argv,const char *prefix) {struct replay_opts opts =REPLAY_OPTS_INIT ; -unsigned flags =0 , keep_empty =0 ; +unsigned flags =0 , keep_empty =0 , rebase_merges =0 ;int abbreviate_commands =0 ;enum {CONTINUE =1 ,ABORT ,MAKE_SCRIPT ,SHORTEN_OIDS ,EXPAND_OIDS ,
@@ -24,6 +24,7 @@ int cmd_rebase__helper(int argc, const char **argv, const char *prefix)OPT_BOOL (0 ,"keep-empty" , &keep_empty,N_ ("keep empty commits" )),OPT_BOOL (0 ,"allow-empty-message" , &opts.allow_empty_message,N_ ("allow commits with empty messages" )), +OPT_BOOL (0 ,"rebase-merges" , &rebase_merges,N_ ("rebase merge commits" )),OPT_CMDMODE (0 ,"continue" , &command,N_ ("continue rebase" ),CONTINUE ), OPT_CMDMODE(0, "abort", &command, N_("abort rebase"),
@@ -57,6 +58,7 @@ int cmd_rebase__helper(int argc, const char **argv, const char *prefix) flags |= keep_empty ?TODO_LIST_KEEP_EMPTY :0 ; flags |= abbreviate_commands ?TODO_LIST_ABBREVIATE_CMDS :0 ; + flags |= rebase_merges ?TODO_LIST_REBASE_MERGES :0 ; flags |= command ==SHORTEN_OIDS ?TODO_LIST_SHORTEN_IDS :0 ;if (command ==CONTINUE && argc ==1 )
sequencer.c +349 -2
378 lines not on this page · raw message
sequencer.h +1 -0
@@ -59,6 +59,7 @@ int sequencer_remove_state(struct replay_opts *opts);#define TODO_LIST_KEEP_EMPTY (1U << 0)#define TODO_LIST_SHORTEN_IDS (1U << 1)#define TODO_LIST_ABBREVIATE_CMDS (1U << 2) +#define TODO_LIST_REBASE_MERGES (1U << 3)int sequencer_make_script (FILE *out,int argc,const char **argv,unsigned flags);
Signature · 1 line
2.17.0.windows.1.15.gaa56ade3205
Re: [PATCH v8 08/16] rebase-helper --make-script: introduce a flag to rebase merges
From: "Johannes Schindelin" <[email protected]>
Sorry for the very late in the series comments..
Quoted 20 lines
The sequencer just learned new commands intended to recreate branch structure (similar in spirit to --preserve-merges, but with a substantially less-broken design).
Let's allow the rebase--helper to generate todo lists making use of these commands, triggered by the new --rebase-merges option. For a commit topology like this (where the HEAD points to C):
- A - B - C
\ / Dthe generated todo list would look like this:
# branch D pick 0123 A label branch-point pick 1234 D label D
Quoted 8 lines
reset branch-point
pick 2345 B
merge -C 3456 D # CTo keep things simple, we first only implement support for merge commits with exactly two parents, leaving support for octopus merges to a later patch series.
For the first time reader this (below) isn't as obvious as may be thought. maybe we should be a little more explicit here.
Quoted 2 lines
As a special, hard-coded label, all merge-rebasing todo lists start with the command
label onto
.. which labels the start point head with the name 'onto' ...
Maybe even:
"All merge-rebasing todo lists start with, as a convenience, a hard-coded label onto line which will label the start point's head" ...
Quoted 449 lines
so that we can later always refer to the revision
onto which everything is rebased.Signed-off-by Johannes Schindelin <[email protected]>---
builtin/rebase--helper.c | 4 +- sequencer.c | 351 ++++++++++++++++++++++++++++++++++++++- sequencer.h | 1 + 3 files changed, 353 insertions(+), 3 deletions(-)builtin/rebase--helper.c +1
-1@@ -12,7 +12,7 @@ static const char * const builtin_rebase_helper_usage[] = {int cmd_rebase__helper (int argc,const char **argv,const char *prefix) {struct replay_opts opts =REPLAY_OPTS_INIT ; -unsigned flags =0 , keep_empty =0 ; +unsigned flags =0 , keep_empty =0 , rebase_merges =0 ;int abbreviate_commands =0 ; enum {CONTINUE = 1, ABORT,
MAKE_SCRIPT,SHORTEN_OIDS,EXPAND_OIDS,builtin/rebase--helper.c +1
-0@@ -24,6 +24,7 @@ int cmd_rebase__helper(int argc, const char **argv, const char *prefix) OPT_BOOL(0, "keep-empty", &keep_empty, N_("keep empty commits")),OPT_BOOL (0 ,"allow-empty-message" , &opts.allow_empty_message,N_ ("allow commits with empty messages" )), +OPT_BOOL (0 ,"rebase-merges" , &rebase_merges,N_ ("rebase merge commits")), OPT_CMDMODE(0, "continue", &command, N_("continue rebase"),CONTINUE),
OPT_CMDMODE(0, "abort", &command,N_("abort rebase"),builtin/rebase--helper.c +1
-0@@ -57,6 +58,7 @@ int cmd_rebase__helper(int argc, const char **argv, const char *prefix) flags |= keep_empty ? TODO_LIST_KEEP_EMPTY : 0; flags |= abbreviate_commands ?TODO_LIST_ABBREVIATE_CMDS :0 ; + flags |= rebase_merges ?TODO_LIST_REBASE_MERGES :0 ; flags |= command ==SHORTEN_OIDS ?TODO_LIST_SHORTEN_IDS :0 ;if (command == CONTINUE && argc == 1)
sequencer.c +339
-0@@ -25,6 +25,8 @@#include "sigchain.h" #include "unpack-trees.h" #include "worktree.h" +#include "oidmap.h" +#include "oidset.h" #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"@@ -3436,6 +3438,343 @@ void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)strbuf_release (&sob); } +struct labels_entry { +struct hashmap_entry entry; +char label[FLEX_ARRAY ]; +}; + +static int labels_cmp (const void *fndata,const struct labels_entry *a, +const struct labels_entry *b,const void *key) +{ +return key ?strcmp (a->label, key) :strcmp (a->label, b->label); +} + +struct string_entry { +struct oidmap_entry entry; +char string[FLEX_ARRAY ]; +}; + +struct label_state { +struct oidmap commit2label; +struct hashmap labels; +struct strbuf buf; +}; + +static const char *label_oid (struct object_id *oid,const char *label, +struct label_state *state) +{ +struct labels_entry *labels_entry; +struct string_entry *string_entry; +struct object_id dummy; +size_t len; +int i; + + string_entry =oidmap_get (&state->commit2label, oid); +if (string_entry) +return string_entry->string; + +/* +* For "uninteresting" commits, i.e. commits that are not to be +* rebased, and which can therefore not be labeled, we use a unique +* abbreviation of the commit name. This is slightly more complicated +* than calling find_unique_abbrev() because we also need to make +* sure that the abbreviation does not conflict with any other +* label. +* +* We disallow "interesting" commits to be labeled by a string that +* is a valid full-length hash, to ensure that we always can find an +* abbreviation for any uninteresting commit's names that does not +* clash with any other label. +*/ +if (!label) { +char *p; + +strbuf_reset (&state->buf); +strbuf_grow (&state->buf,GIT_SHA1_HEXSZ ); + label = p = state->buf.buf; + +find_unique_abbrev_r (p, oid, default_abbrev); + +/* +* We may need to extend the abbreviated hash so that there is +* no conflicting label. +*/ +if (hashmap_get_from_hash (&state->labels,strihash (p), p)) { +size_t i =strlen (p) +1 ; + +oid_to_hex_r (p, oid); +for (; i <GIT_SHA1_HEXSZ ; i++) { +char save = p[i]; + p[i] ='\0' ; +if (!hashmap_get_from_hash (&state->labels, +strihash (p), p)) +break ; + p[i] = save; + } + } + }else if (((len =strlen (label)) ==GIT_SHA1_RAWSZ && + !get_oid_hex (label, &dummy)) || + (len ==1 && *label =='#' ) || +hashmap_get_from_hash (&state->labels, +strihash (label), label)) { +/* +* If the label already exists, or if the label is a valid full +* OID, or the label is a '#' (which we use as a separator +* between merge heads and oneline), we append a dash and a +* number to make it unique. +*/ +struct strbuf *buf = &state->buf; + +strbuf_reset (buf); +strbuf_add (buf, label, len); + +for (i =2 ; ; i++) { +strbuf_setlen (buf, len); +strbuf_addf (buf,"-%d" , i); +if (!hashmap_get_from_hash (&state->labels, +strihash (buf->buf), + buf->buf)) +break ; + } + + label = buf->buf; + } + +FLEX_ALLOC_STR (labels_entry, label, label); +hashmap_entry_init (labels_entry,strihash (label)); +hashmap_add (&state->labels, labels_entry); + +FLEX_ALLOC_STR (string_entry, string, label); +oidcpy (&string_entry->entry.oid, oid); +oidmap_put (&state->commit2label, string_entry); + +return string_entry->string; +} + +static int make_script_with_merges (struct pretty_print_context *pp, +struct rev_info *revs,FILE *out, +unsigned flags) +{ +int keep_empty = flags &TODO_LIST_KEEP_EMPTY ; +struct strbuf buf =STRBUF_INIT , oneline =STRBUF_INIT ; +struct strbuf label =STRBUF_INIT ; +struct commit_list *commits =NULL , **tail = &commits, *iter; +struct commit_list *tips =NULL , **tips_tail = &tips; +struct commit *commit; +struct oidmap commit2todo =OIDMAP_INIT ; +struct string_entry *entry; +struct oidset interesting =OIDSET_INIT , child_seen =OIDSET_INIT , + shown =OIDSET_INIT ; +struct label_state state = {OIDMAP_INIT , {NULL },STRBUF_INIT }; + +int abbr = flags &TODO_LIST_ABBREVIATE_CMDS ; +const char *cmd_pick = abbr ?"p" :"pick" , + *cmd_label = abbr ?"l" :"label" , + *cmd_reset = abbr ?"t" :"reset" , + *cmd_merge = abbr ?"m" :"merge" ; + +oidmap_init (&commit2todo,0 ); +oidmap_init (&state.commit2label,0 ); +hashmap_init (&state.labels, (hashmap_cmp_fn ) labels_cmp,NULL ,0 ); +strbuf_init (&state.buf,32 ); + +if (revs->cmdline.nr && (revs->cmdline.rev[0 ].flags &BOTTOM )) { +struct object_id *oid = &revs->cmdline.rev[0 ].item->oid; +FLEX_ALLOC_STR (entry, string,"onto" ); +oidcpy (&entry->entry.oid, oid); +oidmap_put (&state.commit2label, entry); + } + +/* +* First phase: +* - get onelines for all commits +* - gather all branch tips (i.e. 2nd or later parents of merges) +* - label all branch tips +*/ +while ((commit =get_revision (revs))) { +struct commit_list *to_merge; +int is_octopus; +const char *p1, *p2; +struct object_id *oid; +int is_empty; + + tail = &commit_list_insert (commit, tail)->next; +oidset_insert (&interesting, &commit->object.oid); + + is_empty =is_original_commit_empty (commit); +if (!is_empty && (commit->object.flags &PATCHSAME )) +continue ; + +strbuf_reset (&oneline); +pretty_print_commit (pp, commit, &oneline); + + to_merge = commit->parents ? commit->parents->next :NULL ; +if (!to_merge) { +/* non-merge commit: easy case */ +strbuf_reset (&buf); +if (!keep_empty && is_empty) +strbuf_addf (&buf,"%c " , comment_line_char); +strbuf_addf (&buf,"%s %s %s" , cmd_pick, +oid_to_hex (&commit->object.oid), + oneline.buf); + +FLEX_ALLOC_STR (entry, string, buf.buf); +oidcpy (&entry->entry.oid, &commit->object.oid); +oidmap_put (&commit2todo, entry); + +continue ; + } + + is_octopus = to_merge && to_merge->next; + +if (is_octopus) +BUG ("Octopus merges not yet supported" ); + +/* Create a label */ +strbuf_reset (&label); +if (skip_prefix (oneline.buf,"Merge " , &p1) && + (p1 =strchr (p1,'\'' )) && + (p2 =strchr (++p1,'\'' ))) +strbuf_add (&label, p1, p2 - p1); +else if (skip_prefix (oneline.buf,"Merge pull request " , + &p1) && + (p1 =strstr (p1," from " ))) +strbuf_addstr (&label, p1 +strlen (" from " )); +else +strbuf_addbuf (&label, &oneline); + +for (p1 = label.buf; *p1; p1++) +if (isspace (*p1)) + *(char *)p1 ='-' ; + +strbuf_reset (&buf); +strbuf_addf (&buf,"%s -C %s" , + cmd_merge,oid_to_hex (&commit->object.oid)); + +/* label the tip of merged branch */ + oid = &to_merge->item->object.oid; +strbuf_addch (&buf,' ' ); + +if (!oidset_contains (&interesting, oid)) +strbuf_addstr (&buf,label_oid (oid,NULL , &state)); +else { + tips_tail = &commit_list_insert (to_merge->item, + tips_tail)->next; + +strbuf_addstr (&buf,label_oid (oid, label.buf, &state)); + } +strbuf_addf (&buf," # %s" , oneline.buf); + +FLEX_ALLOC_STR (entry, string, buf.buf); +oidcpy (&entry->entry.oid, &commit->object.oid); +oidmap_put (&commit2todo, entry); + } + +/* +* Second phase: +* - label branch points +* - add HEAD to the branch tips +*/ +for (iter = commits; iter; iter = iter->next) { +struct commit_list *parent = iter->item->parents; +for (; parent; parent = parent->next) { +struct object_id *oid = &parent->item->object.oid; +if (!oidset_contains (&interesting, oid)) +continue ; +if (!oidset_contains (&child_seen, oid)) +oidset_insert (&child_seen, oid); +else +label_oid (oid,"branch-point" , &state); + } + +/* Add HEAD as implict "tip of branch" */ +if (!iter->next) + tips_tail = &commit_list_insert (iter->item, + tips_tail)->next; + } + +/* +* Third phase: output the todo list. This is a bit tricky, as we +* want to avoid jumping back and forth between revisions. To +* accomplish that goal, we walk backwards from the branch tips, +* gathering commits not yet shown, reversing the list on the fly, +* then outputting that list (labeling revisions as needed). +*/ +fprintf (out,"%s onto\n" , cmd_label); +for (iter = tips; iter; iter = iter->next) { +struct commit_list *list =NULL , *iter2; + + commit = iter->item; +if (oidset_contains (&shown, &commit->object.oid)) +continue ; + entry =oidmap_get (&state.commit2label, &commit->object.oid); + +if (entry) +fprintf (out,"\n# Branch %s\n" , entry->string); +else +fprintf (out,"\n" ); + +while (oidset_contains (&interesting, &commit->object.oid) && + !oidset_contains (&shown, &commit->object.oid)) { +commit_list_insert (commit, &list); +if (!commit->parents) { + commit =NULL ; +break ; + } + commit = commit->parents->item; + } + +if (!commit) +fprintf (out,"%s onto\n" , cmd_reset); +else { +const char *to =NULL ; + + entry =oidmap_get (&state.commit2label, + &commit->object.oid); +if (entry) + to = entry->string; + +if (!to || !strcmp (to,"onto" )) +fprintf (out,"%s onto\n" , cmd_reset); +else { +strbuf_reset (&oneline); +pretty_print_commit (pp, commit, &oneline); +fprintf (out,"%s %s # %s\n" , + cmd_reset, to, oneline.buf); + } + } + +for (iter2 = list; iter2; iter2 = iter2->next) { +struct object_id *oid = &iter2->item->object.oid; + entry =oidmap_get (&commit2todo, oid); +/* only show if not already upstream */ +if (entry) +fprintf (out,"%s\n" , entry->string); + entry =oidmap_get (&state.commit2label, oid); +if (entry) +fprintf (out,"%s %s\n" , + cmd_label, entry->string); +oidset_insert (&shown, oid); + } + +free_commit_list (list); + } + +free_commit_list (commits); +free_commit_list (tips); + +strbuf_release (&label); +strbuf_release (&oneline); +strbuf_release (&buf); + +oidmap_free (&commit2todo,1 ); +oidmap_free (&state.commit2label,1 ); +hashmap_free (&state.labels,1 ); +strbuf_release (&state.buf); + +return 0 ; +} +int sequencer_make_script (FILE *out,int argc,const char **argv,unsigned flags){
sequencer.c +7
-2@@ -3446,11 +3785,16 @@ int sequencer_make_script(FILE *out, int argc,const char **argv, struct commit *commit;int keep_empty = flags &TODO_LIST_KEEP_EMPTY ;const char *insn = flags &TODO_LIST_ABBREVIATE_CMDS ?"p" :"pick" ; +int rebase_merges = flags &TODO_LIST_REBASE_MERGES ;init_revisions (&revs,NULL ); revs.verbose_header =1 ; - revs.max_parents =1 ; - revs.cherry_pick =1 ; +if (rebase_merges) + revs.cherry_mark =1 ; +else { + revs.max_parents =1 ; + revs.cherry_pick =1 ; + } revs.limited =1 ; revs.reverse =1 ;revs.right_only = 1;
sequencer.c +3
-0@@ -3474,6 +3818,9 @@ int sequencer_make_script(FILE *out, int argc, const char **argv, if (prepare_revision_walk(&revs) < 0) return error(_("make_script: error preparing revisions")); +if (rebase_merges) +return make_script_with_merges (&pp, &revs, out, flags); +while ((commit =get_revision (&revs))) {strbuf_reset (&buf);if (!keep_empty &&
is_original_commit_empty(commit))sequencer.h +1
-0@@ -59,6 +59,7 @@ int sequencer_remove_state(struct replay_opts *opts);#define TODO_LIST_KEEP_EMPTY (1U << 0)#define TODO_LIST_SHORTEN_IDS (1U << 1)#define TODO_LIST_ABBREVIATE_CMDS (1U << 2) +#define TODO_LIST_REBASE_MERGES (1U << 3)int sequencer_make_script (FILE *out,int argc,const char **argv,unsigned flags);Signature · 1 line
2.17.0.windows.1.15.gaa56ade3205
Re: [PATCH v8 08/16] rebase-helper --make-script: introduce a flag to rebase merges
Hi Philip,
Quoted 35 lines · Philip Oakley
From: "Johannes Schindelin" <[email protected]>
Sorry for the very late in the series comments..
Quoted 20 lines
The sequencer just learned new commands intended to recreate branch structure (similar in spirit to --preserve-merges, but with a substantially less-broken design).
Let's allow the rebase--helper to generate todo lists making use of these commands, triggered by the new --rebase-merges option. For a commit topology like this (where the HEAD points to C):
- A - B - C
\ / Dthe generated todo list would look like this:
# branch D pick 0123 A label branch-point pick 1234 D label DQuoted 8 lines
reset branch-point
pick 2345 B
merge -C 3456 D # CTo keep things simple, we first only implement support for merge commits with exactly two parents, leaving support for octopus merges to a later patch series.
For the first time reader this (below) isn't as obvious as may be thought. maybe we should be a little more explicit here.
Quoted 8 lines
Quoted 2 lines
As a special, hard-coded label, all merge-rebasing todo lists start with the command
label onto.. which labels the start point head with the name 'onto' ...
Maybe even:
"All merge-rebasing todo lists start with, as a convenience, a hard-codedlabel ontoline which will label the start point's head" ...
I changed it to
All merge-rebasing todo lists start with a hard-coded label onto line. This makes it convenient to refer later on to the revision onto which everything is rebased, e.g. as starting point for branches other than the very first one.
Ciao,
Dscho
PATCH v8 9/16 rebase: introduce the --rebase-merges option
In reply to Johannes SchindelinOnce upon a time, this here developer thought: wouldn't it be nice if, say, Git for Windows' patches on top of core Git could be represented as a thicket of branches, and be rebased on top of core Git in order to maintain a cherry-pick'able set of patch series?
The original attempt to answer this was: git rebase --preserve-merges.
However, that experiment was never intended as an interactive option, and it only piggy-backed on git rebase --interactive because that command's implementation looked already very, very familiar: it was designed by the same person who designed --preserve-merges: yours truly.
Some time later, some other developer (I am looking at you, Andreas! ;-)) decided that it would be a good idea to allow --preserve-merges to be combined with --interactive (with caveats!) and the Git maintainer (well, the interim Git maintainer during Junio's absence, that is) agreed, and that is when the glamor of the --preserve-merges design started to fall apart rather quickly and unglamorously.
The reason? In --preserve-merges mode, the parents of a merge commit (or for that matter, of *any* commit) were not stated explicitly, but were *implied* by the commit name passed to the pick command.
This made it impossible, for example, to reorder commits. Not to mention to flatten the branch topology or, deity forbid, to split topic branches into two.
Alas, these shortcomings also prevented that mode (whose original purpose was to serve Git for Windows' needs, with the additional hope that it may be useful to others, too) from serving Git for Windows' needs.
Five years later, when it became really untenable to have one unwieldy, big hodge-podge patch series of partly related, partly unrelated patches in Git for Windows that was rebased onto core Git's tags from time to time (earning the undeserved wrath of the developer of the ill-fated git-remote-hg series that first obsoleted Git for Windows' competing approach, only to be abandoned without maintainer later) was really untenable, the "Git garden shears" were born [*1*/*2*]: a script, piggy-backing on top of the interactive rebase, that would first determine the branch topology of the patches to be rebased, create a pseudo todo list for further editing, transform the result into a real todo list (making heavy use of the exec command to "implement" the missing todo list commands) and finally recreate the patch series on top of the new base commit.
That was in 2013. And it took about three weeks to come up with the design and implement it as an out-of-tree script. Needless to say, the implementation needed quite a few years to stabilize, all the while the design itself proved itself sound.
With this patch, the goodness of the Git garden shears comes to git rebase -i itself. Passing the --rebase-merges option will generate a todo list that can be understood readily, and where it is obvious how to reorder commits. New branches can be introduced by inserting label commands and calling merge <label>. And once this mode will have become stable and universally accepted, we can deprecate the design mistake that was --preserve-merges.
Link *1*:
https://github.com/msysgit/msysgit/blob/master/share/msysGit/shears.sh
Link *2*:
https://github.com/git-for-windows/build-extra/blob/master/shears.sh
--- Documentation/git-rebase.txt | 20 ++- contrib/completion/git-completion.bash | 2 +- git-rebase--interactive.sh | 1 + git-rebase.sh | 6 + t/t3430-rebase-merges.sh | 179 +++++++++++++++++++++++++ 5 files changed, 206 insertions(+), 2 deletions(-) create mode 100755 t/t3430-rebase-merges.sh
Documentation/git-rebase.txt +19 -1
@@ -378,6 +378,23 @@ The commit list format can be changed by setting the configuration option rebase.instructionFormat. A customized instruction format will automatically have the long commit hash prepended to the format. +-r:: +--rebase-merges:: + By default, a rebase will simply drop merge commits and only rebase + the non-merge commits. With this option, it will try to preserve + the branching structure within the commits that are to be rebased, + by recreating the merge commits. If a merge commit resolved any merge + or contained manual amendments, then they will have to be re-applied + manually. ++ +This mode is similar in spirit to `--preserve-merges`, but in contrast to +that option works well in interactive rebases: commits can be reordered, +inserted and dropped at will. ++ +It is currently only possible to recreate the merge commits using the +`recursive` merge strategy; Different merge strategies can be used only via +explicit `exec git merge -s <strategy> [...]` commands. + -p:: --preserve-merges:: Recreate merge commits instead of flattening the history by replaying
@@ -780,7 +797,8 @@ BUGS The todo list presented by `--preserve-merges --interactive` does not represent the topology of the revision graph. Editing commits and rewording their commit messages should work fine, but attempts to -reorder commits tend to produce counterintuitive results. +reorder commits tend to produce counterintuitive results. Use +`--rebase-merges` in such scenarios instead. For example, an attempt to rearrange ------------
contrib/completion/git-completion.bash +1 -1
@@ -1949,7 +1949,7 @@ _git_rebase () --*) __gitcomp " --onto --merge --strategy --interactive - --preserve-merges --stat --no-stat + --rebase-merges --preserve-merges --stat --no-stat --committer-date-is-author-date --ignore-date --ignore-whitespace --whitespace= --autosquash --no-autosquash
git-rebase--interactive.sh +1 -0
@@ -970,6 +970,7 @@ git_rebase__interactive () { init_revisions_and_shortrevisions git rebase--helper --make-script ${keep_empty:+--keep-empty} \ + ${rebase_merges:+--rebase-merges} \ $revisions ${restrict_revision+^$restrict_revision} >"$todo" || die "$(gettext "Could not generate todo list")"
git-rebase.sh +6 -0
@@ -17,6 +17,7 @@ q,quiet! be quiet. implies --no-stat autostash automatically stash/stash pop before and after fork-point use 'merge-base --fork-point' to refine upstream onto=! rebase onto given branch instead of upstream +r,rebase-merges! try to rebase merges instead of skipping them p,preserve-merges! try to recreate merges instead of ignoring them s,strategy=! use the given merge strategy no-ff! cherry-pick all commits, even if unchanged
@@ -88,6 +89,7 @@ type= state_dir= # One of {'', continue, skip, abort}, as parsed from command line action= +rebase_merges= preserve_merges= autosquash= keep_empty=
@@ -270,6 +272,10 @@ do --allow-empty-message) allow_empty_message=--allow-empty-message ;; + --rebase-merges) + rebase_merges=t + test -z "$interactive_rebase" && interactive_rebase=implied + ;; --preserve-merges) preserve_merges=t test -z "$interactive_rebase" && interactive_rebase=implied
t/t3430-rebase-merges.sh new file +179 -0
179 lines not on this page · raw message
Signature · 1 line
2.17.0.windows.1.15.gaa56ade3205
Re: [PATCH v8 09/16] rebase: introduce the --rebase-merges option
From: "Johannes Schindelin" <[email protected]>
Quoted 19 lines
Once upon a time, this here developer thought: wouldn't it be nice if, say, Git for Windows' patches on top of core Git could be represented as a thicket of branches, and be rebased on top of core Git in order to maintain a cherry-pick'able set of patch series?
The original attempt to answer this was: git rebase --preserve-merges.
However, that experiment was never intended as an interactive option, and it only piggy-backed on git rebase --interactive because that command's implementation looked already very, very familiar: it was designed by the same person who designed --preserve-merges: yours truly.
Some time later, some other developer (I am looking at you, Andreas! ;-)) decided that it would be a good idea to allow --preserve-merges to be combined with --interactive (with caveats!) and the Git maintainer (well, the interim Git maintainer during Junio's absence, that is) agreed, and that is when the glamor of the --preserve-merges design started to fall apart rather quickly and unglamorously.
Quoted 4 lines
The reason? In --preserve-merges mode, the parents of a merge commit (or for that matter, of *any* commit) were not stated explicitly, but were *implied* by the commit name passed to the
pickcommand.
Aside: I think this para should be extracted to the --preserve-merges documentation to highlight what it does / why it is 'wrong' (not what would be expected in some case). It may also need to discuss the (figurative) Cousins vs. Siblings distinction [merge of branches external, or internal, to the rebase.
"In --preserve-merges, the commit being selected for merging is implied by the commit name passed to the pick command (i.e. of the original merge commit), not that of the rebased version of that parent."
A similar issue occurs with (figuratively) '--ancestry-path --first parent' searches which lacks the alternate '--lead parent' post-walk selection. [1]. I don't think there is a dot notation to select the merge cousins, nor merge siblings either A.,B ? (that's dot-comma ;-)
Quoted 339 lines
This made it impossible, for example, to reorder commits. Not to mention to flatten the branch topology or, deity forbid, to split topic branches into two.
Alas, these shortcomings also prevented that mode (whose original purpose was to serve Git for Windows' needs, with the additional hope that it may be useful to others, too) from serving Git for Windows' needs.
Five years later, when it became really untenable to have one unwieldy, big hodge-podge patch series of partly related, partly unrelated patches in Git for Windows that was rebased onto core Git's tags from time to time (earning the undeserved wrath of the developer of the ill-fated git-remote-hg series that first obsoleted Git for Windows' competing approach, only to be abandoned without maintainer later) was really untenable, the "Git garden shears" were born [*1*/*2*]: a script, piggy-backing on top of the interactive rebase, that would first determine the branch topology of the patches to be rebased, create a pseudo todo list for further editing, transform the result into a real todo list (making heavy use of the
execcommand to "implement" the missing todo list commands) and finally recreate the patch series on top of the new base commit.That was in 2013. And it took about three weeks to come up with the design and implement it as an out-of-tree script. Needless to say, the implementation needed quite a few years to stabilize, all the while the design itself proved itself sound.
With this patch, the goodness of the Git garden shears comes to
git rebase -iitself. Passing the--rebase-mergesoption will generate a todo list that can be understood readily, and where it is obvious how to reorder commits. New branches can be introduced by insertinglabelcommands and callingmerge <label>. And once this mode will have become stable and universally accepted, we can deprecate the design mistake that was--preserve-merges.Link *1*:
https://github.com/msysgit/msysgit/blob/master/share/msysGit/shears.sh
Link *2*:
https://github.com/git-for-windows/build-extra/blob/master/shears.shSigned-off-by Johannes Schindelin <[email protected]>---
Documentation/git-rebase.txt | 20 ++- contrib/completion/git-completion.bash | 2 +- git-rebase--interactive.sh | 1 + git-rebase.sh | 6 + t/t3430-rebase-merges.sh | 179 +++++++++++++++++++++++++ 5 files changed, 206 insertions(+), 2 deletions(-)create mode 100755
t/t3430-rebase-merges.shDocumentation/git-rebase.txt +0
-0@@ -378,6 +378,23 @@ The commit list format can be changed by setting theconfiguration option
rebase.instructionFormat. A customized instruction format will automatically have the long commit hash prepended to the format.+-r:: +--rebase-merges::+ By default, a rebase will simply drop merge commits and only rebase
+ the non-merge commits. With this option, it will try to preserve
+ the branching structure within the commits that are to be rebased,
+ by recreating the merge commits. If a merge commit resolved any merge
+ or contained manual amendments, then they will have to be re-applied
+ manually.
++Documentation/git-rebase.txt +6
-0+This mode is similar in spirit to `--preserve-merges`, but in contrast to +that option works well in interactive rebases: commits can be reordered, +inserted and dropped at will. ++ +It is currently only possible to recreate the merge commits using the +`recursive` merge strategy; Different merge strategies can be used onlyvia
Documentation/git-rebase.txt +2
-2+explicit `exec git merge -s <strategy> [...]` commands. + -p:: --preserve-merges:: Recreate merge commits instead of flattening the history by replaying@@ -780,7 +797,8 @@ BUGSThe todo list presented by
--preserve-merges --interactivedoes not represent the topology of the revision graph. Editing commits and rewording their commit messages should work fine, but attempts toDocumentation/git-rebase.txt +2
-1-reorder commits tend to produce counterintuitive results. +reorder commits tend to produce counterintuitive results. Use +`--rebase-merges` in such scenarios instead.For example, an attempt to rearrange
------------contrib/completion/git-completion.bash +1
-1@@ -1949,7 +1949,7 @@ _git_rebase () --*) __gitcomp " --onto --merge --strategy --interactive - --preserve-merges --stat --no-stat + --rebase-merges --preserve-merges --stat --no-stat --committer-date-is-author-date --ignore-date --ignore-whitespace --whitespace= --autosquash --no-autosquashgit-rebase--interactive.sh +1
-0@@ -970,6 +970,7 @@ git_rebase__interactive () { init_revisions_and_shortrevisions git rebase--helper --make-script ${keep_empty:+--keep-empty} \ + ${rebase_merges:+--rebase-merges} \ $revisions ${restrict_revision+^$restrict_revision} >"$todo" || die "$(gettext "Could not generate todo list")"git-rebase.sh +0
-0@@ -17,6 +17,7 @@ q,quiet! be quiet. implies --no-statautostash automatically stash/stash pop before and after fork-point use 'merge-base --fork-point' to refine upstream onto=! rebase onto given branch instead of upstream+r,rebase-merges! try to rebase merges instead of skipping them
p,preserve-merges! try to recreate merges instead of ignoring them
s,strategy=! use the given merge strategy
no-ff! cherry-pick all commits, even if unchangedgit-rebase.sh +0
-0@@ -88,6 +89,7 @@ type=state_dir=
# One of {'', continue, skip, abort}, as parsed from command line action=
+rebase_merges=
preserve_merges=
autosquash=
keep_empty=git-rebase.sh +4
-0@@ -270,6 +272,10 @@ do --allow-empty-message) allow_empty_message=--allow-empty-message ;; + --rebase-merges) + rebase_merges=t + test -z "$interactive_rebase" && interactive_rebase=implied + ;; --preserve-merges) preserve_merges=t test -z "$interactive_rebase" && interactive_rebase=impliedt/t3430-rebase-merges.sh new file +8
-0@@ -0,0 +1,179 @@ +#!/bin/sh +# +# Copyright (c) 2018 Johannes E. Schindelin +# + +test_description='git rebase -i --rebase-merges + +This test runs git rebase "interactively", retaining the branch structureby
t/t3430-rebase-merges.sh new file +120
-0+recreating merge commits. + +Initial setup: + + -- B -- (first) + / \ + A - C - D - E - H (master) + \ / + F - G (second) +' +. ./test-lib.sh +. "$TEST_DIRECTORY"/lib-rebase.sh + +test_cmp_graph () { + cat >expect && + git log --graph --boundary --format=%s "$@" >output && + sed "s/ *$//" <output >output.trimmed && + test_cmp expect output.trimmed +} + +test_expect_success 'setup' ' + write_script replace-editor.sh <<-\EOF && + mv "$1" "$(git rev-parse --git-path ORIGINAL-TODO)" + cp script-from-scratch "$1" + EOF + + test_commit A && + git checkout -b first && + test_commit B && + git checkout master && + test_commit C && + test_commit D && + git merge --no-commit B && + test_tick && + git commit -m E && + git tag -m E E && + git checkout -b second C && + test_commit F && + test_commit G && + git checkout master && + git merge --no-commit G && + test_tick && + git commit -m H && + git tag -m H H +' + +test_expect_success 'create completely different structure' ' + cat >script-from-scratch <<-\EOF && + label onto + + # onebranch + pick G + pick D + label onebranch + + # second + reset onto + pick B + label second + + reset onto + merge -C H second + merge onebranch # Merge the topic branch '\''onebranch'\'' + EOF + test_config sequence.editor \""$PWD"/replace-editor.sh\" && + test_tick && + git rebase -i -r A && + test_cmp_graph <<-\EOF + * Merge the topic branch '\''onebranch'\'' + |\ + | * D + | * G + * | H + |\ \ + | |/ + |/| + | * B + |/ + * A + EOF +' + +test_expect_success 'generate correct todo list' ' + cat >expect <<-\EOF && + label onto + + reset onto + pick d9df450 B + label E + + reset onto + pick 5dee784 C + label branch-point + pick ca2c861 F + pick 088b00a G + label H + + reset branch-point # C + pick 12bd07b D + merge -C 2051b56 E # E + merge -C 233d48a H # H + + EOF + + grep -v "^#" <.git/ORIGINAL-TODO >output && + test_cmp expect output +' + +test_expect_success '`reset` refuses to overwrite untracked files' ' + git checkout -b refuse-to-reset && + test_commit dont-overwrite-untracked && + git checkout @{-1} && + : >dont-overwrite-untracked.t && + echo "reset refs/tags/dont-overwrite-untracked" >script-from-scratch && + test_config sequence.editor \""$PWD"/replace-editor.sh\" && + test_must_fail git rebase -r HEAD && + git rebase --abort +' + +test_expect_success 'failed `merge` writes patch (may be rescheduled,too)' '
+test_when_finished"test_might_failgit rebase --abort" &&
+ git checkout -b conflicting-merge A &&t/t3430-rebase-merges.sh new file +49
-0+ + : fail because of conflicting untracked file && + >G.t && + echo "merge -C H G" >script-from-scratch && + test_config sequence.editor \""$PWD"/replace-editor.sh\" && + test_tick && + test_must_fail git rebase -ir HEAD && + grep "^merge -C .* G$" .git/rebase-merge/done && + grep "^merge -C .* G$" .git/rebase-merge/git-rebase-todo && + test_path_is_file .git/rebase-merge/patch && + + : fail because of merge conflict && + rm G.t .git/rebase-merge/patch && + git reset --hard && + test_commit conflicting-G G.t not-G conflicting-G && + test_must_fail git rebase --continue && + ! grep "^merge -C .* G$" .git/rebase-merge/git-rebase-todo && + test_path_is_file .git/rebase-merge/patch +' + +test_expect_success 'with a branch tip that was cherry-picked already' ' + git checkout -b already-upstream master && + base="$(git rev-parse --verify HEAD)" && + + test_commit A1 && + test_commit A2 && + git reset --hard $base && + test_commit B1 && + test_tick && + git merge -m "Merge branch A" A2 && + + git checkout -b upstream-with-a2 $base && + test_tick && + git cherry-pick A2 && + + git checkout already-upstream && + test_tick && + git rebase -i -r upstream-with-a2 && + test_cmp_graph upstream-with-a2.. <<-\EOF + * Merge branch A + |\ + | * A1 + * | B1 + |/ + o A2 + EOF +' + +test_doneSignature · 1 line
2.17.0.windows.1.15.gaa56ade3205
[1]https://public-inbox.org/git/2FA1998250474E76A386B82AD635E56A@PhilipOakley/
Re: [PATCH v8 09/16] rebase: introduce the --rebase-merges option
Hi Philip,
Quoted 24 lines · Philip Oakley
From: "Johannes Schindelin" <[email protected]>
Quoted 19 lines
Once upon a time, this here developer thought: wouldn't it be nice if, say, Git for Windows' patches on top of core Git could be represented as a thicket of branches, and be rebased on top of core Git in order to maintain a cherry-pick'able set of patch series?
The original attempt to answer this was: git rebase --preserve-merges.
However, that experiment was never intended as an interactive option, and it only piggy-backed on git rebase --interactive because that command's implementation looked already very, very familiar: it was designed by the same person who designed --preserve-merges: yours truly.
Some time later, some other developer (I am looking at you, Andreas! ;-)) decided that it would be a good idea to allow --preserve-merges to be combined with --interactive (with caveats!) and the Git maintainer (well, the interim Git maintainer during Junio's absence, that is) agreed, and that is when the glamor of the --preserve-merges design started to fall apart rather quickly and unglamorously.
Quoted 4 lines
The reason? In --preserve-merges mode, the parents of a merge commit (or for that matter, of *any* commit) were not stated explicitly, but were *implied* by the commit name passed to the
pickcommand.
Quoted 5 lines
Aside: I think this para should be extracted to the --preserve-merges documentation to highlight what it does / why it is 'wrong' (not what would be expected in some case). It may also need to discuss the (figurative) Cousins vs. Siblings distinction [merge of branches external, or internal, to the rebase.
Quite honestly, I'd much rather spend time improving --rebase-merges than improving --preserve-merges documentation. In my mind, the latter is pretty useless, especially once the former lands in an official Git version.
Of course, feel free to disagree with me by sending a patch to improve the documentation of --preserve-merges ;-)
Quoted 3 lines
"In --preserve-merges, the commit being selected for merging is implied by the commit name passed to the
pickcommand (i.e. of the original merge commit), not that of the rebased version of that parent."
It is much, much worse:
In --preserve-merges, no commit can change its ancestry. Every rebased commit's parents will be the rebased original parents.
Or some such. But really, why bother describing something *that* broken? Why not work toward a solution that makes that broken option obsolete? Like, say, --rebase-merges? ;-)
Quoted 4 lines
A similar issue occurs with (figuratively) '--ancestry-path --first parent' searches which lacks the alternate '--lead parent' post-walk selection. [1]. I don't think there is a dot notation to select the merge cousins, nor merge siblings either A.,B ? (that's dot-comma ;-)
I actually had missed --ancestry-path... I should probably use it in the description of the "cousins".
Quoted 1 line
[... lots of quoted text...]
Could I ask you to make it easier for me by cutting quoted text that is irrelevant to your reply? The way I read mails forces me to scroll down (sometimes on a phone) all the way to the end, just to find that that time was spent in vain.
Thanks,
Dscho
Re: [PATCH v8 09/16] rebase: introduce the --rebase-merges option
In reply to Johannes SchindelinFrom: "Johannes Schindelin" <[email protected]>
Quoted 19 lines
Once upon a time, this here developer thought: wouldn't it be nice if, say, Git for Windows' patches on top of core Git could be represented as a thicket of branches, and be rebased on top of core Git in order to maintain a cherry-pick'able set of patch series?
The original attempt to answer this was: git rebase --preserve-merges.
However, that experiment was never intended as an interactive option, and it only piggy-backed on git rebase --interactive because that command's implementation looked already very, very familiar: it was designed by the same person who designed --preserve-merges: yours truly.
Some time later, some other developer (I am looking at you, Andreas! ;-)) decided that it would be a good idea to allow --preserve-merges to be combined with --interactive (with caveats!) and the Git maintainer (well, the interim Git maintainer during Junio's absence, that is) agreed, and that is when the glamor of the --preserve-merges design started to fall apart rather quickly and unglamorously.
Quoted 6 lines
The reason? In --preserve-merges mode, the parents of a merge commit (or for that matter, of *any* commit) were not stated explicitly, but were *implied* by the commit name passed to the
pickcommand.This made it impossible, for example, to reorder commits. Not to mention to flatten the branch topology or, deity forbid, to split topic branches
Aside: The idea of a "flattened" topology is, to my mind, not actually defined though may be understood by devs working in the area. Hopefully it's going away as a term, though the new 'cousins' will need clarification (there's no dot notation for that area of topology).
Quoted 75 lines
into two.
Alas, these shortcomings also prevented that mode (whose original purpose was to serve Git for Windows' needs, with the additional hope that it may be useful to others, too) from serving Git for Windows' needs.
Five years later, when it became really untenable to have one unwieldy, big hodge-podge patch series of partly related, partly unrelated patches in Git for Windows that was rebased onto core Git's tags from time to time (earning the undeserved wrath of the developer of the ill-fated git-remote-hg series that first obsoleted Git for Windows' competing approach, only to be abandoned without maintainer later) was really untenable, the "Git garden shears" were born [*1*/*2*]: a script, piggy-backing on top of the interactive rebase, that would first determine the branch topology of the patches to be rebased, create a pseudo todo list for further editing, transform the result into a real todo list (making heavy use of the
execcommand to "implement" the missing todo list commands) and finally recreate the patch series on top of the new base commit.That was in 2013. And it took about three weeks to come up with the design and implement it as an out-of-tree script. Needless to say, the implementation needed quite a few years to stabilize, all the while the design itself proved itself sound.
With this patch, the goodness of the Git garden shears comes to
git rebase -iitself. Passing the--rebase-mergesoption will generate a todo list that can be understood readily, and where it is obvious how to reorder commits. New branches can be introduced by insertinglabelcommands and callingmerge <label>. And once this mode will have become stable and universally accepted, we can deprecate the design mistake that was--preserve-merges.Link *1*:
https://github.com/msysgit/msysgit/blob/master/share/msysGit/shears.sh
Link *2*:
https://github.com/git-for-windows/build-extra/blob/master/shears.shSigned-off-by Johannes Schindelin <[email protected]>---
Documentation/git-rebase.txt | 20 ++- contrib/completion/git-completion.bash | 2 +- git-rebase--interactive.sh | 1 + git-rebase.sh | 6 + t/t3430-rebase-merges.sh | 179 +++++++++++++++++++++++++ 5 files changed, 206 insertions(+), 2 deletions(-)create mode 100755
t/t3430-rebase-merges.shDocumentation/git-rebase.txt +0
-0@@ -378,6 +378,23 @@ The commit list format can be changed by setting theconfiguration option
rebase.instructionFormat. A customized instruction format will automatically
have the long commit hash prepended to the format.+-r:: +--rebase-merges::+ By default, a rebase will simply drop merge commits and only rebase
+ the non-merge commits. With this option, it will try to preserve
+ the branching structure within the commits that are to be rebased,
+ by recreating the merge commits. If a merge commit resolved any merge
+ or contained manual amendments, then they will have to be re-applied
+ manually.
++Documentation/git-rebase.txt +6
-0+This mode is similar in spirit to `--preserve-merges`, but in contrast to +that option works well in interactive rebases: commits can be reordered, +inserted and dropped at will. ++ +It is currently only possible to recreate the merge commits using the +`recursive` merge strategy; Different merge strategies can be used onlyvia
Documentation/git-rebase.txt The commit list format can be changed by setting the configuration option · line 400
Quoted 5 lines
Documentation/git-rebase.txt +2
-2+explicit `exec git merge -s <strategy> [...]` commands. + -p:: --preserve-merges:: Recreate merge commits instead of flattening the history by replaying
Flatten is here in the context lines but its just a blunt statement that 'it is what it is'...
Quoted 259 lines
Documentation/git-rebase.txt +0
-0@@ -780,7 +797,8 @@ BUGSThe todo list presented by
--preserve-merges --interactivedoes not represent the topology of the revision graph. Editing commits and rewording their commit messages should work fine, but attempts toDocumentation/git-rebase.txt +2
-1-reorder commits tend to produce counterintuitive results. +reorder commits tend to produce counterintuitive results. Use +`--rebase-merges` in such scenarios instead.For example, an attempt to rearrange
------------contrib/completion/git-completion.bash +1
-1@@ -1949,7 +1949,7 @@ _git_rebase () --*) __gitcomp " --onto --merge --strategy --interactive - --preserve-merges --stat --no-stat + --rebase-merges --preserve-merges --stat --no-stat --committer-date-is-author-date --ignore-date --ignore-whitespace --whitespace= --autosquash --no-autosquashgit-rebase--interactive.sh +1
-0@@ -970,6 +970,7 @@ git_rebase__interactive () { init_revisions_and_shortrevisions git rebase--helper --make-script ${keep_empty:+--keep-empty} \ + ${rebase_merges:+--rebase-merges} \ $revisions ${restrict_revision+^$restrict_revision} >"$todo" || die "$(gettext "Could not generate todo list")"git-rebase.sh +0
-0@@ -17,6 +17,7 @@ q,quiet! be quiet. implies --no-statautostash automatically stash/stash pop before and after fork-point use 'merge-base --fork-point' to refine upstream onto=! rebase onto given branch instead of upstream+r,rebase-merges! try to rebase merges instead of skipping them
p,preserve-merges! try to recreate merges instead of ignoring them
s,strategy=! use the given merge strategy
no-ff! cherry-pick all commits, even if unchangedgit-rebase.sh +0
-0@@ -88,6 +89,7 @@ type=state_dir=
# One of {'', continue, skip, abort}, as parsed from command line action=
+rebase_merges=
preserve_merges=
autosquash=
keep_empty=git-rebase.sh +4
-0@@ -270,6 +272,10 @@ do --allow-empty-message) allow_empty_message=--allow-empty-message ;; + --rebase-merges) + rebase_merges=t + test -z "$interactive_rebase" && interactive_rebase=implied + ;; --preserve-merges) preserve_merges=t test -z "$interactive_rebase" && interactive_rebase=impliedt/t3430-rebase-merges.sh new file +8
-0@@ -0,0 +1,179 @@ +#!/bin/sh +# +# Copyright (c) 2018 Johannes E. Schindelin +# + +test_description='git rebase -i --rebase-merges + +This test runs git rebase "interactively", retaining the branch structureby
t/t3430-rebase-merges.sh new file +120
-0+recreating merge commits. + +Initial setup: + + -- B -- (first) + / \ + A - C - D - E - H (master) + \ / + F - G (second) +' +. ./test-lib.sh +. "$TEST_DIRECTORY"/lib-rebase.sh + +test_cmp_graph () { + cat >expect && + git log --graph --boundary --format=%s "$@" >output && + sed "s/ *$//" <output >output.trimmed && + test_cmp expect output.trimmed +} + +test_expect_success 'setup' ' + write_script replace-editor.sh <<-\EOF && + mv "$1" "$(git rev-parse --git-path ORIGINAL-TODO)" + cp script-from-scratch "$1" + EOF + + test_commit A && + git checkout -b first && + test_commit B && + git checkout master && + test_commit C && + test_commit D && + git merge --no-commit B && + test_tick && + git commit -m E && + git tag -m E E && + git checkout -b second C && + test_commit F && + test_commit G && + git checkout master && + git merge --no-commit G && + test_tick && + git commit -m H && + git tag -m H H +' + +test_expect_success 'create completely different structure' ' + cat >script-from-scratch <<-\EOF && + label onto + + # onebranch + pick G + pick D + label onebranch + + # second + reset onto + pick B + label second + + reset onto + merge -C H second + merge onebranch # Merge the topic branch '\''onebranch'\'' + EOF + test_config sequence.editor \""$PWD"/replace-editor.sh\" && + test_tick && + git rebase -i -r A && + test_cmp_graph <<-\EOF + * Merge the topic branch '\''onebranch'\'' + |\ + | * D + | * G + * | H + |\ \ + | |/ + |/| + | * B + |/ + * A + EOF +' + +test_expect_success 'generate correct todo list' ' + cat >expect <<-\EOF && + label onto + + reset onto + pick d9df450 B + label E + + reset onto + pick 5dee784 C + label branch-point + pick ca2c861 F + pick 088b00a G + label H + + reset branch-point # C + pick 12bd07b D + merge -C 2051b56 E # E + merge -C 233d48a H # H + + EOF + + grep -v "^#" <.git/ORIGINAL-TODO >output && + test_cmp expect output +' + +test_expect_success '`reset` refuses to overwrite untracked files' ' + git checkout -b refuse-to-reset && + test_commit dont-overwrite-untracked && + git checkout @{-1} && + : >dont-overwrite-untracked.t && + echo "reset refs/tags/dont-overwrite-untracked" >script-from-scratch && + test_config sequence.editor \""$PWD"/replace-editor.sh\" && + test_must_fail git rebase -r HEAD && + git rebase --abort +' + +test_expect_success 'failed `merge` writes patch (may be rescheduled,too)' '
+test_when_finished"test_might_failgit rebase --abort" &&
+ git checkout -b conflicting-merge A &&t/t3430-rebase-merges.sh new file +49
-0+ + : fail because of conflicting untracked file && + >G.t && + echo "merge -C H G" >script-from-scratch && + test_config sequence.editor \""$PWD"/replace-editor.sh\" && + test_tick && + test_must_fail git rebase -ir HEAD && + grep "^merge -C .* G$" .git/rebase-merge/done && + grep "^merge -C .* G$" .git/rebase-merge/git-rebase-todo && + test_path_is_file .git/rebase-merge/patch && + + : fail because of merge conflict && + rm G.t .git/rebase-merge/patch && + git reset --hard && + test_commit conflicting-G G.t not-G conflicting-G && + test_must_fail git rebase --continue && + ! grep "^merge -C .* G$" .git/rebase-merge/git-rebase-todo && + test_path_is_file .git/rebase-merge/patch +' + +test_expect_success 'with a branch tip that was cherry-picked already' ' + git checkout -b already-upstream master && + base="$(git rev-parse --verify HEAD)" && + + test_commit A1 && + test_commit A2 && + git reset --hard $base && + test_commit B1 && + test_tick && + git merge -m "Merge branch A" A2 && + + git checkout -b upstream-with-a2 $base && + test_tick && + git cherry-pick A2 && + + git checkout already-upstream && + test_tick && + git rebase -i -r upstream-with-a2 && + test_cmp_graph upstream-with-a2.. <<-\EOF + * Merge branch A + |\ + | * A1 + * | B1 + |/ + o A2 + EOF +' + +test_doneSignature · 1 line
2.17.0.windows.1.15.gaa56ade3205
Re: [PATCH v8 09/16] rebase: introduce the --rebase-merges option
Quoted 16 lines · Philip Oakley
Quoted 16 lines
+-r:: +--rebase-merges::+ By default, a rebase will simply drop merge commits and only rebase
+ the non-merge commits. With this option, it will try to preserve
+ the branching structure within the commits that are to be rebased,
+ by recreating the merge commits. If a merge commit resolved any merge
+ or contained manual amendments, then they will have to be re-applied
+ manually.
++Documentation/git-rebase.txt +6
-0+This mode is similar in spirit to `--preserve-merges`, but in contrast to +that option works well in interactive rebases: commits can be reordered, +inserted and dropped at will. ++ +It is currently only possible to recreate the merge commits using the +`recursive` merge strategy; Different merge strategies can be used onlyvia
Quoted 8 lines
Documentation/git-rebase.txt The commit list format can be changed by setting the configuration option · line 400
Quoted 5 lines
Documentation/git-rebase.txt +2
-2+explicit `exec git merge -s <strategy> [...]` commands. + -p:: --preserve-merges:: Recreate merge commits instead of flattening the history by replayingFlatten is here in the context lines but its just a blunt statement that 'it is what it is'...
The first paragraph that explains --rebase-merges talks about what happens when the option is not given, and says "drop merge commits and only rebase the non-merge commits", which is not incorrect per-se but does not make it explicit how the resulting topology looks like. I think it is easier to understand if it mentioned "flattening" as well. If flatten is not the word you want, perhaps "make it linear" or something like that?
Re: [PATCH v8 09/16] rebase: introduce the --rebase-merges option
Hi Junio,
Quoted 8 lines · Junio C Hamano
Quoted 6 lines · Philip Oakley
Quoted 6 lines
+-r:: +--rebase-merges::+ By default, a rebase will simply drop merge commits and only rebase
+ the non-merge commits. With this option, it will try to preserve
+ the branching structure within the commits that are to be rebased,
+ by recreating the merge commits. If a merge commit resolved any merge
It is funny how nobody caught the missing "conflicts" in "If a merge commit resolved any merge [conflicts]"...
Quoted 19 lines
Quoted 10 lines
Quoted 10 lines
+ or contained manual amendments, then they will have to be re-applied
+ manually.
++Documentation/git-rebase.txt +6
-0+This mode is similar in spirit to `--preserve-merges`, but in contrast to +that option works well in interactive rebases: commits can be reordered, +inserted and dropped at will. ++ +It is currently only possible to recreate the merge commits using the +`recursive` merge strategy; Different merge strategies can be used onlyvia
Quoted 8 lines
Documentation/git-rebase.txt The commit list format can be changed by setting the configuration option · line 400
Quoted 5 lines
Documentation/git-rebase.txt +2
-2+explicit `exec git merge -s <strategy> [...]` commands. + -p:: --preserve-merges:: Recreate merge commits instead of flattening the history by replayingFlatten is here in the context lines but its just a blunt statement that 'it is what it is'...
Quoted 5 lines
The first paragraph that explains --rebase-merges talks about what happens when the option is not given, and says "drop merge commits and only rebase the non-merge commits", which is not incorrect per-se but does not make it explicit how the resulting topology looks like.
Correct. And it would be the wrong place to describe in detail what a rebase *without --rebase-merges* does, right?
Quoted 3 lines
I think it is easier to understand if it mentioned "flattening" as well. If flatten is not the word you want, perhaps "make it linear" or something like that?
I fear that we all here are way too deeply in "Git think". If I ask a random Git user what it means to "make commits linear", I am sure I would get only puzzled, nervous looks as a response.
So I am rather certain that the suggested wording is something I want to avoid.
Besides, we really should expect the reader to know a little about the way the interactive rebase works by the time they read the explanation of --rebase-merges.
Therefore, I think I can sidestep the entire thing by saying this instead:
-r::
--rebase-merges::
By default, a rebase will simply drop merge commits from the todo list, and put the rebased commits into a single, linear branch. With --rebase-merges, the rebase will instead try to preserve the branching structure within the commits that are to be rebased, by recreating the merge commits. Any resolved merge conflicts or manual amendments in these merge commits will have to be resolved/re-applied manually.
Thank you for helping me improve the documentation part of this patch, which I think is really, really important,
Dscho
Re: [PATCH v8 09/16] rebase: introduce the --rebase-merges option
In reply to Philip OakleyHi Philip,
Quoted 24 lines · Philip Oakley
From: "Johannes Schindelin" <[email protected]>
Quoted 23 lines
Once upon a time, this here developer thought: wouldn't it be nice if, say, Git for Windows' patches on top of core Git could be represented as a thicket of branches, and be rebased on top of core Git in order to maintain a cherry-pick'able set of patch series?
The original attempt to answer this was: git rebase --preserve-merges.
However, that experiment was never intended as an interactive option, and it only piggy-backed on git rebase --interactive because that command's implementation looked already very, very familiar: it was designed by the same person who designed --preserve-merges: yours truly.
Some time later, some other developer (I am looking at you, Andreas! ;-)) decided that it would be a good idea to allow --preserve-merges to be combined with --interactive (with caveats!) and the Git maintainer (well, the interim Git maintainer during Junio's absence, that is) agreed, and that is when the glamor of the --preserve-merges design started to fall apart rather quickly and unglamorously.
The reason? In --preserve-merges mode, the parents of a merge commit (or for that matter, of *any* commit) were not stated explicitly, but were *implied* by the commit name passed to the
pickcommand.
Quoted 7 lines
Quoted 2 lines
This made it impossible, for example, to reorder commits. Not to mention to flatten the branch topology or, deity forbid, to split topic branches
Aside: The idea of a "flattened" topology is, to my mind, not actually defined though may be understood by devs working in the area. Hopefully it's going away as a term, though the new 'cousins' will need clarification (there's no dot notation for that area of topology).
Right. The point is not actually to talk about "flattening" branches. The point is to talk about the flexibility one might expect in an *interactive* rebase, a flexibility notably lacking from the --preserve-merges mode.
So I changed it to
This made it impossible, for example, to reorder commits. Not to mention to move commits between branches or, deity forbid, to split topic branches into two.
Quoted 36 lines
Quoted 6 lines
into two.
Alas, these shortcomings also prevented that mode (whose original purpose was to serve Git for Windows' needs, with the additional hope that it may be useful to others, too) from serving Git for Windows' needs.
[... please feel free to save readers time by culling quoted text that is irrelevant to your reply...]
Quoted 26 lines
Documentation/git-rebase.txt +0
-0@@ -378,6 +378,23 @@ The commit list format can be changed by setting theconfiguration option
rebase.instructionFormat. A customized instruction format will automatically
have the long commit hash prepended to the format.+-r:: +--rebase-merges::+ By default, a rebase will simply drop merge commits and only rebase
+ the non-merge commits. With this option, it will try to preserve
+ the branching structure within the commits that are to be rebased,
+ by recreating the merge commits. If a merge commit resolved any merge
+ or contained manual amendments, then they will have to be re-applied
+ manually.
++Documentation/git-rebase.txt +6
-0+This mode is similar in spirit to `--preserve-merges`, but in contrast to +that option works well in interactive rebases: commits can be reordered, +inserted and dropped at will. ++ +It is currently only possible to recreate the merge commits using the +`recursive` merge strategy; Different merge strategies can be used onlyvia
Quoted 8 lines
Documentation/git-rebase.txt The commit list format can be changed by setting the configuration option · line 400
Quoted 5 lines
Documentation/git-rebase.txt +2
-2+explicit `exec git merge -s <strategy> [...]` commands. + -p:: --preserve-merges:: Recreate merge commits instead of flattening the history by replayingFlatten is here in the context lines but its just a blunt statement that 'it is what it is'...
Correct. This is where that way of expressing things came from.
I will *not* fix the documentation of --preserve-merges, though, as I hope it can be instead retired soon enough.
Ciao,
Dscho
PATCH v8 10/16 rebase --rebase-merges: add test for --keep-empty
In reply to Johannes SchindelinFrom: Phillip Wood <[email protected]>
If there are empty commits on the left hand side of $upstream...HEAD then the empty commits on the right hand side that we want to keep are being pruned.
--- t/t3421-rebase-topology-linear.sh | 1 + 1 file changed, 1 insertion(+)
t/t3421-rebase-topology-linear.sh +1 -0
@@ -217,6 +217,7 @@ test_run_rebase success '' test_run_rebase failure -m test_run_rebase failure -i test_run_rebase failure -p +test_run_rebase success --rebase-merges # m # /
Signature · 1 line
2.17.0.windows.1.15.gaa56ade3205
PATCH v8 11/16 sequencer: make refs generated by the `label` command worktree-local
In reply to Johannes SchindelinThis allows for rebases to be run in parallel in separate worktrees (think: interrupted in the middle of one rebase, being asked to perform a different rebase, adding a separate worktree just for that job).
--- refs.c | 3 ++- t/t3430-rebase-merges.sh | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-)
refs.c +2 -1
@@ -600,7 +600,8 @@ int dwim_log(const char *str, int len, struct object_id *oid, char **log)static int is_per_worktree_ref (const char *refname) {return !strcmp (refname,"HEAD" ) || -starts_with (refname,"refs/bisect/" ); +starts_with (refname,"refs/bisect/" ) || +starts_with (refname,"refs/rewritten/" ); }static int is_pseudoref_syntax (const char *refname)
t/t3430-rebase-merges.sh +14 -0
@@ -176,4 +176,18 @@ test_expect_success 'with a branch tip that was cherry-picked already' ' EOF ' +test_expect_success 'refs/rewritten/* is worktree-local' ' + git worktree add wt && + cat >wt/script-from-scratch <<-\EOF && + label xyz + exec GIT_DIR=../.git git rev-parse --verify refs/rewritten/xyz >a || : + exec git rev-parse --verify refs/rewritten/xyz >b + EOF + + test_config -C wt sequence.editor \""$PWD"/replace-editor.sh\" && + git -C wt rebase -i HEAD && + test_must_be_empty wt/a && + test_cmp_rev HEAD "$(cat wt/b)" +' + test_done
Signature · 1 line
2.17.0.windows.1.15.gaa56ade3205
PATCH v8 12/16 sequencer: handle post-rewrite for merge commands
In reply to Johannes SchindelinIn the previous patches, we implemented the basic functionality of the git rebase -i --rebase-merges command, in particular the merge command to create merge commits in the sequencer.
The interactive rebase is a lot more these days, though, than a simple cherry-pick in a loop. For example, it calls the post-rewrite hook (if any) after rebasing with a mapping of the old->new commits.
This patch implements the post-rewrite handling for the merge command we just introduced. The other commands that were added recently (label and reset) do not create new commits, therefore post-rewrite hooks do not need to handle them.
--- sequencer.c | 5 ++++- t/t3430-rebase-merges.sh | 25 +++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-)
sequencer.c +4 -1
@@ -3062,7 +3062,10 @@ static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts) item->arg, item->arg_len, item->flags, opts)) < 0) reschedule =1 ; - else if (res > 0) + else if (item->commit) + record_in_rewritten(&item->commit->object.oid, + peek_command(todo_list, 1)); +if (res >0 )/* failed with merge conflicts */ return error_with_patch(item->commit, item->arg,
t/t3430-rebase-merges.sh +25 -0
@@ -190,4 +190,29 @@ test_expect_success 'refs/rewritten/* is worktree-local' ' test_cmp_rev HEAD "$(cat wt/b)" ' +test_expect_success 'post-rewrite hook and fixups work for merges' ' + git checkout -b post-rewrite && + test_commit same1 && + git reset --hard HEAD^ && + test_commit same2 && + git merge -m "to fix up" same1 && + echo same old same old >same2.t && + test_tick && + git commit --fixup HEAD same2.t && + fixup="$(git rev-parse HEAD)" && + + mkdir -p .git/hooks && + test_when_finished "rm .git/hooks/post-rewrite" && + echo "cat >actual" | write_script .git/hooks/post-rewrite && + + test_tick && + git rebase -i --autosquash -r HEAD^^^ && + printf "%s %s\n%s %s\n%s %s\n%s %s\n" >expect $(git rev-parse \ + $fixup^^2 HEAD^2 \ + $fixup^^ HEAD^ \ + $fixup^ HEAD \ + $fixup HEAD) && + test_cmp expect actual +' + test_done
Signature · 1 line
2.17.0.windows.1.15.gaa56ade3205
PATCH v8 13/16 rebase --rebase-merges: avoid "empty merges"
In reply to Johannes SchindelinThe git merge command does not allow merging commits that are already reachable from HEAD: git merge HEAD^, for example, will report that we are already up to date and not change a thing.
In an interactive rebase, such a merge could occur previously, e.g. when competing (or slightly modified) versions of a patch series were applied upstream, and the user had to git rebase --skip all of the local commits, and the topic branch becomes "empty" as a consequence.
Let's teach the todo command merge to behave the same as git merge.
Seeing as it requires some low-level trickery to create such merges with Git's commands in the first place, we do not even have to bother to introduce an option to force merge to create such merge commits.
--- sequencer.c | 7 +++++++ t/t3430-rebase-merges.sh | 8 ++++++++ 2 files changed, 15 insertions(+)
sequencer.c +7 -0
@@ -2803,6 +2803,13 @@ static int do_merge(struct commit *commit, const char *arg, int arg_len,write_message ("no-ff" ,5 ,git_path_merge_mode (),0 ); bases =get_merge_bases (head_commit, merge_commit); +if (bases && !oidcmp (&merge_commit->object.oid, + &bases->item->object.oid)) { + ret =0 ; +/* skip merging an ancestor of HEAD */ + goto leave_merge; + } +for (j = bases; j; j = j->next)commit_list_insert (j->item, &reversed);free_commit_list (bases);
t/t3430-rebase-merges.sh +8 -0
@@ -215,4 +215,12 @@ test_expect_success 'post-rewrite hook and fixups work for merges' ' test_cmp expect actual ' +test_expect_success 'refuse to merge ancestors of HEAD' ' + echo "merge HEAD^" >script-from-scratch && + test_config -C wt sequence.editor \""$PWD"/replace-editor.sh\" && + before="$(git rev-parse HEAD)" && + git rebase -i HEAD && + test_cmp_rev HEAD $before +' + test_done
Signature · 1 line
2.17.0.windows.1.15.gaa56ade3205
PATCH v8 14/16 pull: accept --rebase=merges to recreate the branch topology
In reply to Johannes SchindelinSimilar to the preserve mode simply passing the --preserve-merges option to the rebase command, the merges mode simply passes the --rebase-merges option.
This will allow users to conveniently rebase non-trivial commit topologies when pulling new commits, without flattening them.
--- Documentation/config.txt | 8 ++++++++ Documentation/git-pull.txt | 6 +++++- builtin/pull.c | 14 ++++++++++---- builtin/remote.c | 18 ++++++++++++++---- contrib/completion/git-completion.bash | 2 +- 5 files changed, 38 insertions(+), 10 deletions(-)
Documentation/config.txt +8 -0
@@ -1058,6 +1058,10 @@ branch.<name>.rebase:: "git pull" is run. See "pull.rebase" for doing this in a non branch-specific manner. + +When `merges`, pass the `--rebase-merges` option to 'git rebase' +so that the local merge commits are included in the rebase (see +linkgit:git-rebase[1] for details). ++ When preserve, also pass `--preserve-merges` along to 'git rebase' so that locally committed merge commits will not be flattened by running 'git pull'.
@@ -2617,6 +2621,10 @@ pull.rebase:: pull" is run. See "branch.<name>.rebase" for setting this on a per-branch basis. + +When `merges`, pass the `--rebase-merges` option to 'git rebase' +so that the local merge commits are included in the rebase (see +linkgit:git-rebase[1] for details). ++ When preserve, also pass `--preserve-merges` along to 'git rebase' so that locally committed merge commits will not be flattened by running 'git pull'.
Documentation/git-pull.txt +5 -1
@@ -101,13 +101,17 @@ Options related to merging include::merge-options.txt[] -r:: ---rebase[=false|true|preserve|interactive]:: +--rebase[=false|true|merges|preserve|interactive]:: When true, rebase the current branch on top of the upstream branch after fetching. If there is a remote-tracking branch corresponding to the upstream branch and the upstream branch was rebased since last fetched, the rebase uses that information to avoid rebasing non-local changes. + +When set to `merges`, rebase using `git rebase --rebase-merges` so that +the local merge commits are included in the rebase (see +linkgit:git-rebase[1] for details). ++ When set to preserve, rebase with the `--preserve-merges` option passed to `git rebase` so that locally created merge commits will not be flattened. +
builtin/pull.c +10 -4
@@ -27,14 +27,16 @@ enum rebase_type {REBASE_FALSE =0 ,REBASE_TRUE ,REBASE_PRESERVE , +REBASE_MERGES , REBASE_INTERACTIVE };/** * Parses the value of --rebase. If value is a false value, returns * REBASE_FALSE. If value is a true value, returns REBASE_TRUE. If value is -* "preserve", returns REBASE_PRESERVE. If value is a invalid value, dies with -* a fatal error if fatal is true, otherwise returns REBASE_INVALID. +* "merges", returns REBASE_MERGES. If value is "preserve", returns +* REBASE_PRESERVE. If value is a invalid value, dies with a fatal error if +* fatal is true, otherwise returns REBASE_INVALID. */ static enum rebase_type parse_config_rebase (const char *key,const char *value,int fatal)
@@ -47,6 +49,8 @@ static enum rebase_type parse_config_rebase(const char *key, const char *value,return REBASE_TRUE ; else if (!strcmp(value, "preserve"))return REBASE_PRESERVE ; + else if (!strcmp(value, "merges")) +return REBASE_MERGES ; else if (!strcmp(value, "interactive"))return REBASE_INTERACTIVE ;
@@ -130,7 +134,7 @@ static struct option pull_options[] = {/* Options passed to git-merge or git-rebase */ OPT_GROUP (N_ ("Options related to merging" )), { OPTION_CALLBACK, 'r', "rebase", &opt_rebase, -"false|true|preserve|interactive" , +"false|true|merges|preserve|interactive" ,N_ ("incorporate changes by rebasing rather than merging" ), PARSE_OPT_OPTARG, parse_opt_rebase }, OPT_PASSTHRU('n', NULL, &opt_diffstat, NULL,
@@ -800,7 +804,9 @@ static int run_rebase(const struct object_id *curr_head,argv_push_verbosity (&args);/* Options passed to git-rebase */ -if (opt_rebase ==REBASE_PRESERVE ) +if (opt_rebase ==REBASE_MERGES ) +argv_array_push (&args,"--rebase-merges" ); +else if (opt_rebase ==REBASE_PRESERVE )argv_array_push (&args,"--preserve-merges" );else if (opt_rebase ==REBASE_INTERACTIVE )argv_array_push (&args,"--interactive" );
builtin/remote.c +14 -4
@@ -245,7 +245,9 @@ static int add(int argc, const char **argv)struct branch_info {char *remote_name;struct string_list merge; -enum {NO_REBASE ,NORMAL_REBASE ,INTERACTIVE_REBASE } rebase; +enum { +NO_REBASE ,NORMAL_REBASE ,INTERACTIVE_REBASE ,REBASE_MERGES + } rebase; };static struct string_list branch_list =STRING_LIST_INIT_NODUP ;
@@ -306,6 +308,8 @@ static int config_read_branches(const char *key, const char *value, void *cb) info->rebase = v; else if (!strcmp(value, "preserve")) info->rebase =NORMAL_REBASE ; + else if (!strcmp(value, "merges")) + info->rebase =REBASE_MERGES ; else if (!strcmp(value, "interactive")) info->rebase =INTERACTIVE_REBASE ; }
@@ -963,9 +967,15 @@ static int show_local_info_item(struct string_list_item *item, void *cb_data)printf (" %-*s " , show_info->width, item->string);if (branch_info->rebase) { -printf_ln (branch_info->rebase ==INTERACTIVE_REBASE - ?_ ("rebases interactively onto remote %s" ) - :_ ("rebases onto remote %s" ), merge->items[0 ].string); +const char *msg; +if (branch_info->rebase ==INTERACTIVE_REBASE ) + msg =_ ("rebases interactively onto remote %s" ); +else if (branch_info->rebase ==REBASE_MERGES ) + msg =_ ("rebases interactively (with merges) onto " +"remote %s" ); +else + msg =_ ("rebases onto remote %s" ); +printf_ln (msg, merge->items[0 ].string);return 0 ; }else if (show_info->any_rebase) {printf_ln (_ (" merges with remote %s" ), merge->items[0 ].string);
contrib/completion/git-completion.bash +1 -1
@@ -2120,7 +2120,7 @@ _git_config () return ;; branch.*.rebase) - __gitcomp "false true preserve interactive" + __gitcomp "false true merges preserve interactive" return ;; remote.pushdefault)
Signature · 1 line
2.17.0.windows.1.15.gaa56ade3205
PATCH v8 15/16 rebase -i: introduce --rebase-merges=[no-]rebase-cousins
In reply to Johannes SchindelinThis one is a bit tricky to explain, so let's try with a diagram:
C
/ \A - B - E - F
\ /
D
To illustrate what this new mode is all about, let's consider what happens upon git rebase -i --rebase-merges B, in particular to the commit D. So far, the new branch structure would be:
--- C' --
/ \
A - B ------ E' - F'
\ /
D'This is not really preserving the branch topology from before! The reason is that the commit D does not have B as ancestor, and therefore it gets rebased onto B.
This is unintuitive behavior. Even worse, when recreating branch structure, most use cases would appear to want cousins *not* to be rebased onto the new base commit. For example, Git for Windows (the heaviest user of the Git garden shears, which served as the blueprint for --rebase-merges) frequently merges branches from next early, and these branches certainly do *not* want to be rebased. In the example above, the desired outcome would look like this:
--- C' --
/ \A - B ------ E' - F'
\ /
-- D' --
Let's introduce the term "cousins" for such commits ("D" in the example), and let's not rebase them by default, introducing the new "rebase-cousins" mode for use cases where they should be rebased.
--- Documentation/git-rebase.txt | 7 ++++++- builtin/rebase--helper.c | 9 ++++++++- git-rebase--interactive.sh | 1 + git-rebase.sh | 12 +++++++++++- sequencer.c | 4 ++++ sequencer.h | 6 ++++++ t/t3430-rebase-merges.sh | 18 ++++++++++++++++++ 7 files changed, 54 insertions(+), 3 deletions(-)
Documentation/git-rebase.txt +6 -1
@@ -379,7 +379,7 @@ rebase.instructionFormat. A customized instruction format will automatically have the long commit hash prepended to the format. -r:: ---rebase-merges:: +--rebase-merges[=(rebase-cousins|no-rebase-cousins)]:: By default, a rebase will simply drop merge commits and only rebase the non-merge commits. With this option, it will try to preserve the branching structure within the commits that are to be rebased,
@@ -387,6 +387,11 @@ have the long commit hash prepended to the format. or contained manual amendments, then they will have to be re-applied manually. + +By default, or when `no-rebase-cousins` was specified, commits which do not +have `<upstream>` as direct ancestor will keep their original branch point. +If the `rebase-cousins` mode is turned on, such commits are instead rebased +onto `<upstream>` (or `<onto>`, if specified). ++ This mode is similar in spirit to `--preserve-merges`, but in contrast to that option works well in interactive rebases: commits can be reordered, inserted and dropped at will.
builtin/rebase--helper.c +8 -1
@@ -13,7 +13,7 @@ int cmd_rebase__helper(int argc, const char **argv, const char *prefix) {struct replay_opts opts =REPLAY_OPTS_INIT ;unsigned flags =0 , keep_empty =0 , rebase_merges =0 ; -int abbreviate_commands =0 ; +int abbreviate_commands =0 , rebase_cousins =-1 ;enum {CONTINUE =1 ,ABORT ,MAKE_SCRIPT ,SHORTEN_OIDS ,EXPAND_OIDS ,CHECK_TODO_LIST ,SKIP_UNNECESSARY_PICKS ,REARRANGE_SQUASH ,
@@ -25,6 +25,8 @@ int cmd_rebase__helper(int argc, const char **argv, const char *prefix)OPT_BOOL (0 ,"allow-empty-message" , &opts.allow_empty_message,N_ ("allow commits with empty messages" )),OPT_BOOL (0 ,"rebase-merges" , &rebase_merges,N_ ("rebase merge commits" )), +OPT_BOOL (0 ,"rebase-cousins" , &rebase_cousins, +N_ ("keep original branch points of cousins" )),OPT_CMDMODE (0 ,"continue" , &command,N_ ("continue rebase" ),CONTINUE ), OPT_CMDMODE(0, "abort", &command, N_("abort rebase"),
@@ -59,8 +61,13 @@ int cmd_rebase__helper(int argc, const char **argv, const char *prefix) flags |= keep_empty ?TODO_LIST_KEEP_EMPTY :0 ; flags |= abbreviate_commands ?TODO_LIST_ABBREVIATE_CMDS :0 ; flags |= rebase_merges ?TODO_LIST_REBASE_MERGES :0 ; + flags |= rebase_cousins >0 ?TODO_LIST_REBASE_COUSINS :0 ; flags |= command ==SHORTEN_OIDS ?TODO_LIST_SHORTEN_IDS :0 ; +if (rebase_cousins >=0 && !rebase_merges) +warning (_ ("--[no-]rebase-cousins has no effect without " +"--rebase-merges" )); +if (command ==CONTINUE && argc ==1 )return !!sequencer_continue (&opts);if (command ==ABORT && argc ==1 )
git-rebase--interactive.sh +1 -0
@@ -971,6 +971,7 @@ git_rebase__interactive () { git rebase--helper --make-script ${keep_empty:+--keep-empty} \ ${rebase_merges:+--rebase-merges} \ + ${rebase_cousins:+--rebase-cousins} \ $revisions ${restrict_revision+^$restrict_revision} >"$todo" || die "$(gettext "Could not generate todo list")"
git-rebase.sh +11 -1
@@ -17,7 +17,7 @@ q,quiet! be quiet. implies --no-stat autostash automatically stash/stash pop before and after fork-point use 'merge-base --fork-point' to refine upstream onto=! rebase onto given branch instead of upstream -r,rebase-merges! try to rebase merges instead of skipping them +r,rebase-merges? try to rebase merges instead of skipping them p,preserve-merges! try to recreate merges instead of ignoring them s,strategy=! use the given merge strategy no-ff! cherry-pick all commits, even if unchanged
@@ -90,6 +90,7 @@ state_dir= # One of {'', continue, skip, abort}, as parsed from command line action= rebase_merges= +rebase_cousins= preserve_merges= autosquash= keep_empty=
@@ -276,6 +277,15 @@ do rebase_merges=t test -z "$interactive_rebase" && interactive_rebase=implied ;; + --rebase-merges=*) + rebase_merges=t + case "${1#*=}" in + rebase-cousins) rebase_cousins=t;; + no-rebase-cousins) rebase_cousins=;; + *) die "Unknown mode: $1";; + esac + test -z "$interactive_rebase" && interactive_rebase=implied + ;; --preserve-merges) preserve_merges=t test -z "$interactive_rebase" && interactive_rebase=implied
sequencer.c +4 -0
@@ -3566,6 +3566,7 @@ static int make_script_with_merges(struct pretty_print_context *pp, unsigned flags) {int keep_empty = flags &TODO_LIST_KEEP_EMPTY ; +int rebase_cousins = flags &TODO_LIST_REBASE_COUSINS ;struct strbuf buf =STRBUF_INIT , oneline =STRBUF_INIT ;struct strbuf label =STRBUF_INIT ;struct commit_list *commits =NULL , **tail = &commits, *iter;
@@ -3743,6 +3744,9 @@ static int make_script_with_merges(struct pretty_print_context *pp, &commit->object.oid);if (entry) to = entry->string; +else if (!rebase_cousins) + to =label_oid (&commit->object.oid,NULL , + &state);if (!to || !strcmp (to,"onto" ))fprintf (out,"%s onto\n" , cmd_reset);
sequencer.h +6 -0
@@ -60,6 +60,12 @@ int sequencer_remove_state(struct replay_opts *opts);#define TODO_LIST_SHORTEN_IDS (1U << 1)#define TODO_LIST_ABBREVIATE_CMDS (1U << 2)#define TODO_LIST_REBASE_MERGES (1U << 3) +/* +* When rebasing merges, commits that do have the base commit as ancestor +* ("cousins") are *not* rebased onto the new base by default. If those +* commits should be rebased onto the new base, this flag needs to be passed. +*/ +#define TODO_LIST_REBASE_COUSINS (1U << 4)int sequencer_make_script (FILE *out,int argc,const char **argv,unsigned flags);
t/t3430-rebase-merges.sh +18 -0
@@ -176,6 +176,24 @@ test_expect_success 'with a branch tip that was cherry-picked already' ' EOF ' +test_expect_success 'do not rebase cousins unless asked for' ' + git checkout -b cousins master && + before="$(git rev-parse --verify HEAD)" && + test_tick && + git rebase -r HEAD^ && + test_cmp_rev HEAD $before && + test_tick && + git rebase --rebase-merges=rebase-cousins HEAD^ && + test_cmp_graph HEAD^.. <<-\EOF + * Merge the topic branch '\''onebranch'\'' + |\ + | * D + | * G + |/ + o H + EOF +' + test_expect_success 'refs/rewritten/* is worktree-local' ' git worktree add wt && cat >wt/script-from-scratch <<-\EOF &&
Signature · 1 line
2.17.0.windows.1.15.gaa56ade3205
PATCH v8 16/16 rebase -i --rebase-merges: add a section to the man page
In reply to Johannes SchindelinThe --rebase-merges mode is probably not half as intuitive to use as its inventor hopes, so let's document it some.
--- Documentation/git-rebase.txt | 135 +++++++++++++++++++++++++++++++++++ 1 file changed, 135 insertions(+)
Documentation/git-rebase.txt +135 -0
@@ -399,6 +399,8 @@ inserted and dropped at will. It is currently only possible to recreate the merge commits using the `recursive` merge strategy; Different merge strategies can be used only via explicit `exec git merge -s <strategy> [...]` commands. ++ +See also REBASING MERGES below. -p:: --preserve-merges::
@@ -797,6 +799,139 @@ The ripple effect of a "hard case" recovery is especially bad: 'everyone' downstream from 'topic' will now have to perform a "hard case" recovery too! +REBASING MERGES +----------------- + +The interactive rebase command was originally designed to handle +individual patch series. As such, it makes sense to exclude merge +commits from the todo list, as the developer may have merged the +then-current `master` while working on the branch, only to rebase +all the commits onto `master` eventually (skipping the merge +commits). + +However, there are legitimate reasons why a developer may want to +recreate merge commits: to keep the branch structure (or "commit +topology") when working on multiple, inter-related branches. + +In the following example, the developer works on a topic branch that +refactors the way buttons are defined, and on another topic branch +that uses that refactoring to implement a "Report a bug" button. The +output of `git log --graph --format=%s -5` may look like this: + +------------ +* Merge branch 'report-a-bug' +|\ +| * Add the feedback button +* | Merge branch 'refactor-button' +|\ \ +| |/ +| * Use the Button class for all buttons +| * Extract a generic Button class from the DownloadButton one +------------ + +The developer might want to rebase those commits to a newer `master` +while keeping the branch topology, for example when the first topic +branch is expected to be integrated into `master` much earlier than the +second one, say, to resolve merge conflicts with changes to the +DownloadButton class that made it into `master`. + +This rebase can be performed using the `--rebase-merges` option. +It will generate a todo list looking like this: + +------------ +label onto + +# Branch: refactor-button +reset onto +pick 123456 Extract a generic Button class from the DownloadButton one +pick 654321 Use the Button class for all buttons +label refactor-button + +# Branch: report-a-bug +reset refactor-button # Use the Button class for all buttons +pick abcdef Add the feedback button +label report-a-bug + +reset onto +merge -C a1b2c3 refactor-button # Merge 'refactor-button' +merge -C 6f5e4d report-a-bug # Merge 'report-a-bug' +------------ + +In contrast to a regular interactive rebase, there are `label`, `reset` +and `merge` commands in addition to `pick` ones. + +The `label` command associates a label with the current HEAD when that +command is executed. These labels are created as worktree-local refs +(`refs/rewritten/<label>`) that will be deleted when the rebase +finishes. That way, rebase operations in multiple worktrees linked to +the same repository do not interfere with one another. If the `label` +command fails, it is rescheduled immediately, with a helpful message how +to proceed. + +The `reset` command resets the HEAD, index and worktree to the specified +revision. It is isimilar to an `exec git reset --hard <label>`, but +refuses to overwrite untracked files. If the `reset` command fails, it is +rescheduled immediately, with a helpful message how to edit the todo list +(this typically happens when a `reset` command was inserted into the todo +list manually and contains a typo). + +The `merge` command will merge the specified revision into whatever is +HEAD at that time. With `-C <original-commit>`, the commit message of +the specified merge commit will be used. When the `-C` is changed to +a lower-case `-c`, the message will be opened in an editor after a +successful merge so that the user can edit the message. + +If a `merge` command fails for any reason other than merge conflicts (i.e. +when the merge operation did not even start), it is rescheduled immediately. + +At this time, the `merge` command will *always* use the `recursive` +merge strategy, with no way to choose a different one. To work around +this, an `exec` command can be used to call `git merge` explicitly, +using the fact that the labels are worktree-local refs (the ref +`refs/rewritten/onto` would correspond to the label `onto`, for example). + +Note: the first command (`label onto`) labels the revision onto which +the commits are rebased; The name `onto` is just a convention, as a nod +to the `--onto` option. + +It is also possible to introduce completely new merge commits from scratch +by adding a command of the form `merge <merge-head>`. This form will +generate a tentative commit message and always open an editor to let the +user edit it. This can be useful e.g. when a topic branch turns out to +address more than a single concern and wants to be split into two or +even more topic branches. Consider this todo list: + +------------ +pick 192837 Switch from GNU Makefiles to CMake +pick 5a6c7e Document the switch to CMake +pick 918273 Fix detection of OpenSSL in CMake +pick afbecd http: add support for TLS v1.3 +pick fdbaec Fix detection of cURL in CMake on Windows +------------ + +The one commit in this list that is not related to CMake may very well +have been motivated by working on fixing all those bugs introduced by +switching to CMake, but it addresses a different concern. To split this +branch into two topic branches, the todo list could be edited like this: + +------------ +label onto + +pick afbecd http: add support for TLS v1.3 +label tlsv1.3 + +reset onto +pick 192837 Switch from GNU Makefiles to CMake +pick 918273 Fix detection of OpenSSL in CMake +pick fdbaec Fix detection of cURL in CMake on Windows +pick 5a6c7e Document the switch to CMake +label cmake + +reset onto +merge tlsv1.3 +merge cmake +------------ + BUGS ---- The todo list presented by `--preserve-merges --interactive` does not
Signature · 1 line
2.17.0.windows.1.15.gaa56ade3205
v9 cover rebase -i: offer to recreate commit topology by rebasing merges
In reply to Johannes SchindelinJunio, I think this is now ready for next. Thank you for your patience and help with this.
Once upon a time, I dreamed of an interactive rebase that would not linearize all patches and drop all merge commits, but instead recreate the commit topology faithfully.
My original attempt was --preserve-merges, but that design was so limited that I did not even enable it in interactive mode.
Subsequently, it *was* enabled in interactive mode, with the predictable
consequences: as the --preserve-merges design does not allow for specifying the parents of merge commits explicitly, all the new commits' parents are defined *implicitly* by the previous commit history, and hence it is *not possible to even reorder commits*.
This design flaw cannot be fixed. Not without a complete re-design, at least. This patch series offers such a re-design.
Think of --rebase-merges as "--preserve-merges done right". It introduces new verbs for the todo list, label, reset and merge. For a commit topology like this:
A - B - C
\ /
D
the generated todo list would look like this:
# branch D
pick 0123 A
label branch-point
pick 1234 D
label D reset branch-point
pick 2345 B
merge -C 3456 D # CThere are more patches in the pipeline, based on this patch series, but left for later in the interest of reviewable patch series: one mini series to use the sequencer even for git rebase -i --root, and another one to add support for octopus merges to --rebase-merges. And then one to allow for rebasing merge commits in a smarter way (this one will need a bit more work, though, as it can result in very complicated, nested merge conflicts *very* easily).
Changes since v8:
- Disentangled the patch introducing label/reset from the one introducing merge again (this was one stupid, tired git commit --amend too many).
- Augmented the commit message of "introduce the merge command" to describe what the label onto is all about.
- Fixed the error message when reset would overwrite untracked files to actually say that a "reset" failed (not a "merge").
- Clarified the rationale for label onto in the commit message of "rebase-helper --make-script: introduce a flag to rebase merges".
- Edited the description of --rebase-merges heavily, for clarity, in "rebase: introduce the --rebase-merges option".
- Edited the commit message of (and the documentation introduced by) " rebase -i: introduce --rebase-merges=[no-]rebase-cousins" for clarity (also mentioning the --ancestry-path option).
- When run_git_commit() fails after a successful merge, we now take pains not to reschedule the merge command.
- Rebased the patch series on top of current master, i.e. both pw/rebase-keep-empty-fixes and pw/rebase-signoff, to resolve merge conflicts myself.
Johannes Schindelin (15):
sequencer: avoid using errno clobbered by rollback_lock_file()
sequencer: make rearrange_squash() a bit more obvious
sequencer: refactor how original todo list lines are accessed
sequencer: offer helpful advice when a command was rescheduled
sequencer: introduce new commands to reset the revision
sequencer: introduce the merge command
sequencer: fast-forward merge commands, if possible rebase-helper --make-script: introduce a flag to rebase merges
rebase: introduce the --rebase-merges option
sequencer: make refs generated by the label command worktree-local
sequencer: handle post-rewrite for merge commands
rebase --rebase-merges: avoid "empty merges"
pull: accept --rebase=merges to recreate the branch topology rebase -i: introduce --rebase-merges=[no-]rebase-cousins rebase -i --rebase-merges: add a section to the man page
Phillip Wood (1):
rebase --rebase-merges: add test for --keep-empty
Stefan Beller (1):
git-rebase--interactive: clarify arguments
Documentation/config.txt | 8 + Documentation/git-pull.txt | 6 +- Documentation/git-rebase.txt | 163 ++++- builtin/pull.c | 14 +- builtin/rebase--helper.c | 13 +- builtin/remote.c | 18 +- contrib/completion/git-completion.bash | 4 +- git-rebase--interactive.sh | 22 +- git-rebase.sh | 16 + refs.c | 3 +- sequencer.c | 892 ++++++++++++++++++++++++- sequencer.h | 7 + t/t3421-rebase-topology-linear.sh | 1 + t/t3430-rebase-merges.sh | 244 +++++++ 14 files changed, 1352 insertions(+), 59 deletions(-) create mode 100755 t/t3430-rebase-merges.sh
base-commit: 1f1cddd558b54bb0ce19c8ace353fd07b758510d
Published-As: https://github.com/dscho/git/releases/tag/recreate-merges-v9
Fetch-It-Via: git fetch https://github.com/dscho/git recreate-merges-v9
Interdiff vs v8:
diff --git a/Documentation/git-rebase.txt b/Documentation/git-rebase.txt index e691b93e920..bd5ecff980e 100644
--- a/Documentation/git-rebase.txt
+++ b/Documentation/git-rebase.txt
@@ -381,21 +381,24 @@ have the long commit hash prepended to the format.
-r::
--rebase-merges[=(rebase-cousins|no-rebase-cousins)]::
- By default, a rebase will simply drop merge commits and only rebase
- the non-merge commits. With this option, it will try to preserve
+ By default, a rebase will simply drop merge commits from the todo
+ list, and put the rebased commits into a single, linear branch.
+ With --rebase-merges, the rebase will instead try to preserve
the branching structure within the commits that are to be rebased,
- by recreating the merge commits. If a merge commit resolved any merge
- or contained manual amendments, then they will have to be re-applied
- manually.
+ by recreating the merge commits. Any resolved merge conflicts or
+ manual amendments in these merge commits will have to be
+ resolved/re-applied manually.
+
By default, or when no-rebase-cousins was specified, commits which do not
-have <upstream> as direct ancestor will keep their original branch point. -If the rebase-cousins mode is turned on, such commits are instead rebased +have <upstream> as direct ancestor will keep their original branch point, +i.e. commits that would be excluded by gitlink:git-log[1]'s
+--ancestry-path option will keep their original ancestry by default. If
+the rebase-cousins mode is turned on, such commits are instead rebased
onto <upstream> (or <onto>, if specified).
+
-This mode is similar in spirit to --preserve-merges, but in contrast to -that option works well in interactive rebases: commits can be reordered, -inserted and dropped at will.
+The --rebase-merges mode is similar in spirit to --preserve-merges, but +in contrast to that option works well in interactive rebases: commits can be +reordered, inserted and dropped at will.
+
It is currently only possible to recreate the merge commits using the recursive merge strategy; Different merge strategies can be used only via
diff --git a/sequencer.c b/sequencer.c
index b5715f69450..e2f83942843 100644
--- a/sequencer.c
+++ b/sequencer.c
@@ -2635,6 +2635,7 @@ static int do_reset(const char *name, int len, struct replay_opts *opts)
}
memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
+ setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
unpack_tree_opts.head_idx = 1;
unpack_tree_opts.src_index = &the_index;
unpack_tree_opts.dst_index = &the_index;
@@ -2855,7 +2856,12 @@ static int do_merge(struct commit *commit, const char *arg, int arg_len,
if (ret)
rerere(opts->allow_rerere_auto);
else
- ret = run_git_commit(git_path_merge_msg(), opts,
+ /*
+ * In case of problems, we now want to return a positive
+ * value (a negative one would indicate that the merge
+ * command needs to be rescheduled).
+ */
+ ret = !!run_git_commit(git_path_merge_msg(), opts,
run_commit_flags);
leave_merge:
@@ -3809,12 +3815,9 @@ int sequencer_make_script(FILE *out, int argc, const char **argv,
init_revisions(&revs, NULL);
revs.verbose_header = 1;
- if (rebase_merges)
- revs.cherry_mark = 1;
- else {
+ if (!rebase_merges)
revs.max_parents = 1;
- revs.cherry_pick = 1;
- }
+ revs.cherry_mark = 1;
revs.limited = 1;
revs.reverse = 1;
revs.right_only = 1;
Signature · 1 line
2.17.0.windows.1.33.gfcbb1fa0445
PATCH v9 1/17 sequencer: avoid using errno clobbered by rollback_lock_file()
As pointed out in a review of the --rebase-merges patch series, rollback_lock_file() clobbers errno. Therefore, we have to report the error message that uses errno before calling said function.
--- sequencer.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-)
sequencer.c +6 -4
@@ -346,12 +346,14 @@ static int write_message(const void *buf, size_t len, const char *filename,if (msg_fd <0 )return error_errno (_ ("could not lock '%s'" ), filename);if (write_in_full (msg_fd, buf, len) <0 ) { +error_errno (_ ("could not write to '%s'" ), filename);rollback_lock_file (&msg_file); -return error_errno (_ ("could not write to '%s'" ), filename); +return -1 ; }if (append_eol &&write (msg_fd,"\n" ,1 ) <0 ) { +error_errno (_ ("could not write eol to '%s'" ), filename);rollback_lock_file (&msg_file); -return error_errno (_ ("could not write eol to '%s'" ), filename); +return -1 ; }if (commit_lock_file (&msg_file) <0 )return error (_ ("failed to finalize '%s'" ), filename);
@@ -2125,9 +2127,9 @@ static int save_head(const char *head) written =write_in_full (fd, buf.buf, buf.len);strbuf_release (&buf);if (written <0 ) { +error_errno (_ ("could not write to '%s'" ),git_path_head_file ());rollback_lock_file (&head_lock); -return error_errno (_ ("could not write to '%s'" ), -git_path_head_file ()); +return -1 ; }if (commit_lock_file (&head_lock) <0 )return error (_ ("failed to finalize '%s'" ),git_path_head_file ());
Signature · 1 line
2.17.0.windows.1.33.gfcbb1fa0445
PATCH v9 2/17 sequencer: make rearrange_squash() a bit more obvious
In reply to Johannes SchindelinThere are some commands that have to be skipped from rearranging by virtue of not handling any commits.
However, the logic was not quite obvious: it skipped commands based on their position in the enum todo_command.
Instead, let's make it explicit that we skip all commands that do not handle any commit. With one exception: the drop command, because it, well, drops the commit and is therefore not eligible to rearranging.
Note: this is a bit academic at the moment because the only time we call rearrange_squash() is directly after generating the todo list, when we have nothing but pick commands anyway.
However, the upcoming merge command *will* want to be handled by that function, and it *can* handle commits.
--- sequencer.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
sequencer.c +1 -1
@@ -3403,7 +3403,7 @@ int rearrange_squash(void)struct subject2item_entry *entry; next[i] = tail[i] =-1 ; -if (item->command >=TODO_EXEC ) { +if (!item->commit || item->command ==TODO_DROP ) { subjects[i] =NULL ;continue ; }
Signature · 1 line
2.17.0.windows.1.33.gfcbb1fa0445
PATCH v9 3/17 sequencer: refactor how original todo list lines are accessed
In reply to Johannes SchindelinPreviously, we did a lot of arithmetic gymnastics to get at the line in the todo list (as stored in todo_list.buf). This might have been fast, but only in terms of execution speed, not in terms of developer time.
Let's refactor this to make it a lot easier to read, and hence to reason about the correctness of the code. It is not performance-critical code anyway.
--- sequencer.c | 60 ++++++++++++++++++++++++++++++++--------------------- 1 file changed, 36 insertions(+), 24 deletions(-)
sequencer.c +36 -24
@@ -1871,6 +1871,23 @@ static int count_commands(struct todo_list *todo_list)return count; } +static int get_item_line_offset (struct todo_list *todo_list,int index) +{ +return index < todo_list->nr ? + todo_list->items[index].offset_in_buf : todo_list->buf.len; +} + +static const char *get_item_line (struct todo_list *todo_list,int index) +{ +return todo_list->buf.buf +get_item_line_offset (todo_list, index); +} + +static int get_item_line_length (struct todo_list *todo_list,int index) +{ +return get_item_line_offset (todo_list, index +1 ) + -get_item_line_offset (todo_list, index); +} +static ssize_t strbuf_read_file_or_whine (struct strbuf *sb,const char *path) {int fd;
@@ -2250,29 +2267,27 @@ static int save_todo(struct todo_list *todo_list, struct replay_opts *opts) fd =hold_lock_file_for_update (&todo_lock, todo_path,0 );if (fd <0 )return error_errno (_ ("could not lock '%s'" ), todo_path); - offset = next < todo_list->nr ? - todo_list->items[next].offset_in_buf : todo_list->buf.len; + offset =get_item_line_offset (todo_list, next);if (write_in_full (fd, todo_list->buf.buf + offset, todo_list->buf.len - offset) <0 )return error_errno (_ ("could not write to '%s'" ), todo_path);if (commit_lock_file (&todo_lock) <0 )return error (_ ("failed to finalize '%s'" ), todo_path); -if (is_rebase_i (opts)) { -const char *done_path =rebase_path_done (); -int fd =open (done_path,O_CREAT |O_WRONLY |O_APPEND ,0666 ); -int prev_offset = !next ?0 : - todo_list->items[next -1 ].offset_in_buf; +if (is_rebase_i (opts) && next >0 ) { +const char *done =rebase_path_done (); +int fd =open (done,O_CREAT |O_WRONLY |O_APPEND ,0666 ); +int ret =0 ; -if (fd >=0 && offset > prev_offset && -write_in_full (fd, todo_list->buf.buf + prev_offset, - offset - prev_offset) <0 ) { -close (fd); -return error_errno (_ ("could not write to '%s'" ), - done_path); - } -if (fd >=0 ) -close (fd); +if (fd <0 ) +return 0 ; +if (write_in_full (fd,get_item_line (todo_list, next -1 ), +get_item_line_length (todo_list, next -1 )) + <0 ) + ret =error_errno (_ ("could not write to '%s'" ), done); +if (close (fd) <0 ) + ret =error_errno (_ ("failed to finalize '%s'" ), done); +return ret; }return 0 ; }
@@ -3307,8 +3322,7 @@ int skip_unnecessary_picks(void) oid = &item->commit->object.oid; }if (i >0 ) { -int offset = i < todo_list.nr ? - todo_list.items[i].offset_in_buf : todo_list.buf.len; +int offset =get_item_line_offset (&todo_list, i);const char *done_path =rebase_path_done (); fd =open (done_path,O_CREAT |O_WRONLY |O_APPEND ,0666 );
@@ -3488,12 +3502,10 @@ int rearrange_squash(void)continue ;while (cur >=0 ) { -int offset = todo_list.items[cur].offset_in_buf; -int end_offset = cur +1 < todo_list.nr ? - todo_list.items[cur +1 ].offset_in_buf : - todo_list.buf.len; -char *bol = todo_list.buf.buf + offset; -char *eol = todo_list.buf.buf + end_offset; +const char *bol = +get_item_line (&todo_list, cur); +const char *eol = +get_item_line (&todo_list, cur +1 );/* replace 'pick', by 'fixup' or 'squash' */ command = todo_list.items[cur].command;
Signature · 1 line
2.17.0.windows.1.33.gfcbb1fa0445