问题
I want to checkout to other branch, or previous commit, but I want to keep one folder the same files (not checkout the folder).
I want that the folder, will be shown in git status
, so I can add this folder now to the index.
For example, I have a folder with node_modules
. I want the folder to be in all my commits (I know that most of the people prefer to .gitignore the node_modules
folder). But when I move to other commit, or checkut other branch, I want that git
will not touch the node_modules
folder.
Is it possible?
回答1:
You could use sparse checkout to exclude the committed contents of the node_modules
directory from the working tree. As the documentation says:
"Sparse checkout" allows populating the working directory sparsely. It uses the
skip-worktree
bit to tell Git whether a file in the working directory is worth looking at.
Here's how you use it. First, you enable the sparseCheckout
option:
git config core.sparseCheckout true
Then, you add the node_modules
path as a negation in the .git/info/sparse-checkout
file:
echo -e "/*\n!node_modules" >> .git/info/sparse-checkout
This will create a file called sparse-checkout
containing:
/*
!node_modules
which effectively means ignore the node_modules
directory when reading a commit's tree into the working directory.
If you later want to include the node_modules
directory again (i.e. remove the skip-worktree bit from its files) you have to modify the sparse-checkout
file to only contain /*
– that is "include all paths" – and update your working directory using git read-tree
:
echo "/*" > .git/info/sparse-checkout
git read-tree -mu HEAD
You can then disable sparse checkout altogether by setting its configuration variable to false
:
git config core.sparseCheckout false
Note that sparse checkout was first introduced in Git 1.7.0.
来源:https://stackoverflow.com/questions/33933702/git-checkout-except-one-folder