Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GIT checkout except one folder

Tags:

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?

like image 603
Aminadav Glickshtein Avatar asked Nov 26 '15 08:11

Aminadav Glickshtein


2 Answers

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.

like image 191
Enrico Campidoglio Avatar answered Sep 17 '22 12:09

Enrico Campidoglio


I checked out the entire code from the branch I want to checkout

# assume we want the `components` folder on my-branch to follow us

# first checkout your code to (my-new-branch) for ex.
git checkout -b my-new-branch

# now i'm on my-new-branch (but it doesn't have the components from my-branch :| )

# delete ./components
rm -rf ./components 

# replace it with the one on my-branch :)
git checkout my-branch -- ./components 

Good Luck...

like image 40
Aakash Avatar answered Sep 21 '22 12:09

Aakash