Home > front end >  How To Revert A Specific File in the Commit at GitHub Desktop
How To Revert A Specific File in the Commit at GitHub Desktop

Time:04-09

I pushed the X commit to my feature branch.

When I check history via Github Desktop, I realize just one file doesn't need to be in this commit: History seems like as below:

X commit
A file changed-- ok
B file changed-- ok
C file changed-- not ok for me.. I had changed this by mistake.

Is there any way to go back to this original file (the state before my commit) without reverting the commit?

My only way is to find the file from the origin-develop and copy and paste my feature branch and make a new commit for this.

CodePudding user response:

Is there any way to go back to this original file (the state before my commit) without reverting the commit?

Certainly. The file's state before this commit is sitting there in the previous commit. (All commits are snapshots of all the files.)

What you cannot do, however, is alter the commit you have made. Commits are immutable; Git would be pretty useless otherwise.

My only way is to find the file from the origin-develop and copy and paste my feature branch and make a new commit for this.

Yes, and...? So do that.

If what you object to is that you then have two commits where you would prefer to have one, then squash them together after making the second commit; interactive rebase is an easy way to do that, though personally in this situation I would use soft reset, as explained in my What's the difference between git reset --mixed, --soft, and --hard? (this is Regret Type 1).


Example. We start with this situation:

* 78f90c1 edited all three files
* 5ec87ed created three files

We edited three files; call them aaa.txt, bbb.txt, and ccc.txt. We regret the edit of ccc.txt and wish to restore it, and it alone, to the state that it was in 5ec87ed.

git restore -s @~1 -- ccc.txt
git add .
git commit -m 'restored ccc.txt'

Done. We now have this:

* 75c192b (HEAD -> what) restored the third file
* 78f90c1 edited all three files
* 5ec87ed created three files

But if we prefer to have only one commit where now we have two:

% git reset --soft @~2
% git commit -m 'edited just two files'

Result:

* e0a324a (HEAD -> what) edited just two files
* 5ec87ed created three files
  • Related