How to git reset --hard a subdirectory?
According to Git developer Duy Nguyen who kindly implemented the feature and a compatibility switch, the following works as expected as of Git 1.8.3:
git checkout -- a
(where a
is the directory you want to hard-reset). The original behavior can be accessed via
git checkout --ignore-skip-worktree-bits -- a
With Git 2.23 (August 2019), you have the new command git restore
(also presented here)
git restore --source=HEAD --staged --worktree -- aDirectory
# or, shorter
git restore -s@ -SW -- aDirectory
That would replace both the index and working tree with HEAD
content, like an reset --hard
would, but for a specific path.
Original answer (2013)
Note (as commented by Dan Fabulich) that:
git checkout -- <path>
doesn't do a hard reset: it replaces the working tree contents with the staged contents.git checkout HEAD -- <path>
does a hard reset for a path, replacing both the index and the working tree with the version from theHEAD
commit.
As answered by Ajedi32, both checkout forms don't remove files which were deleted in the target revision.
If you have extra files in the working tree which don't exist in HEAD, a git checkout HEAD -- <path>
won't remove them.
Note: With git checkout --overlay HEAD -- <path>
(Git 2.22, Q1 2019), files that appear in the index and working tree, but not in <tree-ish>
are removed, to make them match <tree-ish>
exactly.
But that checkout can respect a git update-index --skip-worktree
(for those directories you want to ignore), as mentioned in "Why do excluded files keep reappearing in my git sparse checkout?".
Try changing
git checkout -- a
to
git checkout -- `git ls-files -m -- a`
Since version 1.7.0, Git's ls-files
honors the skip-worktree flag.
Running your test script (with some minor tweaks changing git commit
... to git commit -q
and git status
to git status --short
) outputs:
Initialized empty Git repository in /home/user/repo/.git/
After read-tree:
a/a/aa
a/b/ab
b/a/ba
After modifying:
b/a/ba
D a/a/aa
D a/b/ab
M b/a/ba
After checkout:
M b/a/ba
a/a/aa
a/c/ac
a/b/ab
b/a/ba
Running your test script with the proposed checkout
change outputs:
Initialized empty Git repository in /home/user/repo/.git/
After read-tree:
a/a/aa
a/b/ab
b/a/ba
After modifying:
b/a/ba
D a/a/aa
D a/b/ab
M b/a/ba
After checkout:
M b/a/ba
a/a/aa
a/b/ab
b/a/ba