Home > Mobile >  Git - restore single folder from a push that had multiple folders
Git - restore single folder from a push that had multiple folders

Time:09-16

I have a folder/file structure on my local machine thus:

project1/
  ----.git/
  ----src/
     file1.cpp, ..., file10.cpp
  ----include/
     incl1.h, ..., incl10.h
  .gitignore

This was committed and pushed to the online repository. Since then, I have modified files both under /src/ and under /include/ locally. However, I now realize that changes made locally since the push under /src/ are wrong. The changes made locally under /include/ are fine. I would now like to locally keep the good changes I made to files under /include/ and restore locally only the /src/ folder to the state it was in before -- i.e., I want only the /src/ folder locally to be exactly like the latest push to the online repository. The /include/ folder should remain unchanged locally.

That is, I do not want to replicate locally exactly the entirety of the online repository, but only specific folders/files inside of it.

CodePudding user response:

Have you committed the unwanted changes locally?

If not, there are a couple of approaches you can take.

One is to use git checkout with a path name, e.g. git checkout src/ will reset the files in the src directory back to their state as of the current head commit.

The other approach is to selectively add and commit the files/directories where you do want to keep the changes. Then once the only changes left between the working tree and the committed state are ones you don't want to keep, you can nuke them with git reset --hard.


If you have committed the changes locally then again you have multiple options. Depending on what aspects of the local history you want to keep.

One option is to use git reset --mixed origin/master (replace origin/master with the name of the remote and remote branch). This will undo the local adding/commiting of changes, but leave the local changes in the working tree where they can be dealt with as-if you had never committed them.

Another is to use git checkout origin/master src/ then make a new commit, this will result in a history that includes the addition and reversion

There are other option involving things like filter branch or interactive rebase that let you preserve the structure of local commits while altering their content, but I'm not familiar enough with those myself to write detailed instructions,

  •  Tags:  
  • git
  • Related