Home > OS >  How to edit an old commit without affecting the one after it
How to edit an old commit without affecting the one after it

Time:12-12

I have 2 commits, let's call them A and B, B is a good commit but A has some files that need to be deleted, and I'm kinda new to git so I don't really know what to do in this situation.

using bitbucket btw.

CodePudding user response:

A more appropriate solution is likely a git rebase. Where commit B, is left untouched and commit A is edited.

For example.

git rebase -i HEAD~2

will rebase 2 commits from HEAD. where HEAD is the current commit

git will next prompt you to describe what you want to do with each commit. Find commit A in the list and replace the first word with edit then quit & save (it's likely that you are in vim). This will leave your git in a state where you can go ahead and make edits such as git rm -f --cached somefile.txt.

Upon completion of your edits, simply run git rebase --continue & there you have it. An edited commit A using git rebase

CodePudding user response:

Here are 2 mechanisms for updating commits (none of them actually update commits - they are immutable):

  1. You create a new commit based on another one (many ways of doing it with amend, rebase, reset, filter-branch). Your next commits must also start referencing the new one, therefore those commits also must be copied. All of the commits will acquire new hashes. If no one references the old commits, then at some point they will be GC'ed.
  2. git replace the commit with another one. This keeps the old and the new commit. It's just whenever Git sees a reference to the old one, it pretends to reference another one.

First option is a true way of removing commits and their data from git repository. But it's intrusive and requires a force push. Second option is light-weight and doesn't require the history of commits to be re-created. But it doesn't really delete the bad commits and data they point to - it's still possible to find them, it simply becomes harder.

  • Related