Search code examples
gitgit-revert

Revert changes from a single directory in git


I cannot find a good match for this, but there must be a shorter way of doing this... Say we have a sub-tree of a project, picking one at random here, as a local repository and I want to rewind back to the December 11th revision 6b6e73b3e77176a8a80ae01a1844914102728acd, that is undo the six (at the time of writing) commits above. From reading the docs, I know I could do:

git revert commit1 commit2 commit3 commit4 commit5 commit6

But surely there must be an easier and more general way like, say:

git revert HEAD...6b6e73b3e77176a8a80ae01a1844914102728acd \
        src/vs/editor/contrib/codelens

That gives me "fatal: bad revision 'src/vs/editor/contrib/codelens'".

Of course, doing:

git checkout 6b6e73b3e77176a8a80ae01a1844914102728acd \
        src/vs/editor/contrib/codelens

Gives me the desired revision for the given directory, but I'd like to have a git-generated revert log for traceability, etc.


Solution

  • I've experimented and come to the conclusion this is not a good idea, but in the spirit of sharing, this is what I came up with. First, to get a list of versions to revert, I did:

    git log --first-parent --no-merges --pretty=format:"%h" \
                      HEAD...6b6e73b3e77176a8a80ae01a1844914102728acd .
    

    So, to feed that into git revert, I did:

    git revert --no-commit $(git log --first-parent --no-merges --pretty=format:"%h" \
                      HEAD...6b6e73b3e77176a8a80ae01a1844914102728acd .)
    

    However, on my own repository things got messy and there were lots of merge conflicts, so I just gave up and did:

    git revert --abort
    git checkout 6b6e73b3e77176a8a80ae01a1844914102728acd \
            src/vs/editor/contrib/codelens
    

    Then manually added the results of:

    git log --first-parent --no-merges --oneline \
                      HEAD...6b6e73b3e77176a8a80ae01a1844914102728acd .
    

    To the commit message.