In a git repository I have a subdirectory that I want to reset to a specific state in the past (an earlier commit). Is it possible to undo all commits on files in a specific subdirectory? I think there are no commits that apply changes to files within this subdirectory and on files located elsewhere at the same time. But it would be nice if it were possible to leave commits on files unaffected that are not located in this directory?
I don't need to remove the history. It would be no problem to checkout the old state, remove the current content of the subdirectory, and copy and commit the old state in its place. But eventually there may be a more elegant (gitonic) way.
git reset --hard is a classic command in this situation - but it will only discard changes in tracked files (i.e. files that already are under version control). To get rid of new / untracked files, you'll have to use git clean !
There are two Git commands a developer must use in order to discard all local changes in Git, remove all uncommited changes and revert their Git working tree back to the state it was in when the last commit took place. The commands to discard all local changes in Git are: git reset –hard. git clean -fxd.
The simplest way to do it to use the ability of git checkout
to be applied on a subdirectory. Then stage and commit:
git checkout <old-SHA1> -- path/to/subdir
git add -A path/to/subdir
git commit -m "reverted files in path/to/subdir to what it was at <old-SHA1>"
If you work out all of the commits that you want to undo, you can use git revert to back them out - this would be most useful if there was only one or two commits that were the troublemakers.
CharlesB's answer is a simpler approach to take if there are lots of commits, or the commits touch other parts of the project (but you could actually work around that by using the -n (don't autocommit) flag, and only committing the changes you are interested in)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With