UPDATE²: With Git 2.23 (August 2019), there’s a new command
git restore
that does this, see the accepted answer.UPDATE: This will work more intuitively as of Git 1.8.3, see my own answer.
Imagine the following use case: I want to get rid of all changes in a specific subdirectory of my Git working tree, leaving all other subdirectories intact.
-
I can do
git checkout .
, but git checkout . adds directories excluded by sparse checkout -
There is
git reset --hard
, but it won’t let me do it for a subdirectory:> git reset --hard . fatal: Cannot do hard reset with paths.
Again: Why git can’t do hard/soft resets by path?
-
I can reverse-patch the current state using
git diff subdir | patch -p1 -R
, but this is a rather weird way of doing this.
What is the proper Git command for this operation?
The script below illustrates the problem. Insert the proper command below the How to make files
comment — the current command will restore the file a/c/ac
which is supposed to be excluded by the sparse checkout. Note that I do not want to explicitly restore a/a
and a/b
, I only “know” a
and want to restore everything below. EDIT: And I also don’t “know” b
, or which other directories reside on the same level as a
.
#!/bin/sh
rm -rf repo; git init repo; cd repo
for f in a b; do
for g in a b c; do
mkdir -p $f/$g
touch $f/$g/$f$g
git add $f/$g
git commit -m "added $f/$g"
done
done
git config core.sparsecheckout true
echo a/a > .git/info/sparse-checkout
echo a/b >> .git/info/sparse-checkout
echo b/a >> .git/info/sparse-checkout
git read-tree -m -u HEAD
echo "After read-tree:"
find * -type f
rm a/a/aa
rm a/b/ab
echo >> b/a/ba
echo "After modifying:"
find * -type f
git status
# How to make files a/* reappear without changing b and without recreating a/c?
git checkout -- a
echo "After checkout:"
git status
find * -type f