Elliot Chance
Elliot Chance

Reputation: 5736

How do I edit a commit with interactive rebase as uncommited?

I would like to use an interactive rebase to edit a previous commit, but when I enter the edit mode for that commit all the files have been committed.

I know I can make changes and amend the commit but I want all the changes uncommitted initially (staged or otherwise) so I can edit it as if it was moments before it was originally committed. Is this possible?

Upvotes: 4

Views: 796

Answers (3)

acran
acran

Reputation: 8943

Imagine git rebase --interactive gives you this list:

pick 3d15626 first
pick 7911b8b second
pick 60d94b4 third

and you now want to edit the second commit in its un-committed state. For this change its line like the this:

pick 3d15626 first
exec git cherry-pick --no-commit 7911b8b && false
pick 60d94b4 third

What this line does:

  • instead of picking the commit normally git cherry-pick is executed
  • git cherry-pick will apply the "second" commit (note the same commit hash used) to the index and the working tree, preload the commit message but not commit (--no-commit)
  • && false ensures that the executed command "fails" by returning a failing exit code. This forces git rebase to break after this line to let you "fix" the problem, i.e. you can now edit the commit
  • after you are done editing you can git commit it again. The editor will automatically contain the original commit message thanks to git cherry-pick
  • after you committed the commit and the index is clean again you can continue with git rebase --continue

Upvotes: 8

TheMeaningfulEngineer
TheMeaningfulEngineer

Reputation: 16329

An extension on @VonC answer with an example of the situation:

mkdir git_example
cd git_example
git init
echo first > first
git add first 
git commit -m "initial"
git tag initial

echo "How do I see this change while editing in interacive rebase" > second
git add second 
git commit -m "second"

echo third > third
git add third 
git commit -m "third"

git rebase -i initial
    e 66127f1 second
    pick 70c0b50 third

git reset HEAD~
git add .
git commit  
# NOT commit --amend
# The commit message will be empty, that's ok
git rebase --continue

Being explicit about one thing that messed my mind a bit:

After the reset do a commit not a commit --amend or that will mess up the initial commit.

Upvotes: 2

VonC
VonC

Reputation: 1323353

You can at least reset to the previous commit, add everything and commit: you will then able to set again the commit message.

 git reset @~
 git add .
 git commit --interactive

Or actually just git commit, since you already added what you wanted.
That would still open an editor for you to enter the commit message again.

Upvotes: 2

Related Questions