Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git interactive rebase, edit particular commit without needing to use editor?

Tags:

git

rebase

Currently I need to do: git rebase -i f47adfa0 which show me:

pick 447a1cb Either left or right
pick ef35186 Introducing side effects

I then modify it to:

edit 447a1cb Either left or right
pick ef35186 Introducing side effects

If I would like to edit a particular commit (447a1cb in this case) is there a command I can use to invoke that state directly? Rather than having to go through the above procedure?

like image 663
Chris Stryczynski Avatar asked Mar 24 '18 13:03

Chris Stryczynski


2 Answers

IIUC, you can create a temporary branch and then merge it back with rebase:

 $ git checkout -b temp-branch <SHA1>
 $ git commit --amend -m 'new commit message'
 $ git checkout -
 $ git rebase @{-1}
 $ git branch -d @{-1}
like image 30
Arkadiusz Drabczyk Avatar answered Sep 24 '22 18:09

Arkadiusz Drabczyk


I cannot think of a quick way to do this. Here is one way. It works regardless of how far back the commit happens to be, but note that the rebase will eat any merges along the way.*

git checkout 447a1cb
<edit stuff>
git commit --amend
git checkout -
git rebase --onto @{-1} 447a1cb

Note that I have used the commit hash 447a1cb explicitly above in the first and last step; this can of course be replaced by a relative reference such as HEAD^ as long as the same commit is referenced in both steps.

The above explained:

  1. Check out the commit to be edited directly (note: you will be in "detached HEAD" state, this means any changes here will not affect the branch you had checked out before this step, until you make that happen in step 5).
  2. Edit what you need to edit
  3. Amend the commit with the new changes
  4. Check out what was previously checked out, i.e. the branch if you had one
  5. Rebase the branch onto the commit checked out before (4), ignoring the commit at HEAD^ (the first parent of the last commit, i.e. one commit back) and earlier. Using --onto will avoid also applying the old commit, which could lead to conflicts or an additional commit.

More info at man git-rebase.

While the above method works, I would probably prefer interactive rebase most of the time.


* If there are merges after the commit you are editing, consider either the --preserve-merges flag to git rebase (but read the BUGS part man git-rebase) --rebase-merges flag to git rebase, or instead use git replace --edit in combination with git filter-branch. More info at man git-replace and man git-filter-branch.

like image 66
jsageryd Avatar answered Sep 25 '22 18:09

jsageryd