How to undo git sparse-checkout add

110 views Asked by At

Let's say I did a sparse checkout of a partial clone to not get everything from a big Git repo:

git clone --filter=blob:none --sparse https://example.com/url/of/my/repo.git
cd repo
git sparse-checkout add Boost/boost_1_77_0

How can I then undo git sparse-checkout add Boost/boost_1_77_0 to remove the directory locally (but not from the server's branch) ?

1

There are 1 answers

0
Gabriel Devillers On

As of today there is no command to undo git sparse-checkout add according to the documentation.

Here is a manual solution that requires modifying a config file within the .git directory: proceed with care.

This solution assumes you are in cone mode which is likely because it is the default mode.

This solution assumes you did do a matching git sparse-checkout add i.e. you would have to tweak it if you did a bigger add and want to un-add a smaller set of files than what you took with git sparse-checkout add.

Note that this solution will not reduce the size of the clone as much as theoretically possible because currently local blobs cannot be deleted from a clone, however if you do not use Git LFS there is compression so the space you do not regain is usually less than the size of deleted files (if blobs size is 30% of the files size you will go from 130% of space usage to 30% of space usage).

Manual Solution

  1. Make a backup of .git/info/sparse-checkout, just in case
  2. Work from a clean state: run the command git status. It should not show anything added, changed, deleted or untracked. This is not strictly necessary but recommended to help you understand what is going on in the next steps.
  3. Run git pull to be up-to-date.
  4. Remove the directory from your clone (in your example Boost/boost_1_77_0). If you run git status you should see it's content removed. Do not git add or git rm or git commit these deletions: they must stay at worktree level.
  5. Remove the line of .git/info/sparse-checkout corresponding to the directory (in your example Boost/boost_1_77_0/):
/Boost/boost_1_77_0/
  1. If the parent directory becomes empty (it is the case in your example: Boost/ is now empty) and you do not need the files it contains (see note below), you have two more lines to remove:
/Boost/
!/Boost/*/
  1. Iterate until reaching a parent directory which is not empty, or the root of the clone (in this example there is no need to iterate as Boost/ is at the root)
  2. Run the command git sparse-checkout reapply. It should run without error.
  3. Run the command git status. It should not show any removed file.

Note on step 6.: in cone mode you get the files (not directories) which are contained inside all added directories or their parent directories, so be careful to not do this step if you rely on some of these files - or do git sparse-checkout add those you need afterward.