Search code examples
windowsgitcheckoutsparse-checkout

Git sparse checkout a subfolder into a different location inside my repo folder


Let's assume we have a Git repo with a three-level subfolder:

|_
|_Folder1
|_Folder2
        |_ SubFolder2
                    |_ SubSubFolder2

I need to sparse checkout this folder and place it into a different location inside C:\MyRepo folder (on Windows) - get rid of leading Folder2 directory:

C:\MyRepo
        |_ SubFolder2
                    |_ SubSubFolder2

Is that possible somehow or Git sparse checkout always respect original (remote repo) folder structure and that cannot be changed?

P.S. I've tried the following standard code:

git clone --no-checkout --sparse <remoteRepoURL> "C:\MyRepo"
cd /d "C:\MyRepo"
git sparse-checkout set "Folder2/SubFolder2/SubSubFolder2"
git checkout

But I get original (remote repo) folder structure:

C:\MyRepo
        |_Folder2
                |_ SubFolder2
                            |_ SubSubFolder2

Is there a way to change that default behaviour?

P.P.S. There was a similar question asked 7 years ago - still no clear answer there..


Solution

  • In git-bash, first read the tree into a temporary index file.

    GIT_INDEX_FILE=/tmp/.tmp.index git read-tree ${revision}:${parent_dir}
    
    # In your case it could be
    GIT_INDEX_FILE=/tmp/.tmp.index git read-tree HEAD:_Folder2
    

    Then, checkout the folders and files from the index to the destination.

    GIT_INDEX_FILE=/tmp/.tmp.index git checkout-index -f -a --prefix=/c/MyRepo/
    

    Remove the temporary index. We can also use the command mktemp to create a random tempfile, avoiding naming conflicts.

    rm -rf /tmp/.tmp.index
    

    Note that on Windows /c/MyRepo/ could also be c:\\MyRepo\\. The ending / and \\ cannot be missing.

    For Windows CMD (I tried with Microsoft Windows [Version 10.0.19042.1165]),

    set GIT_INDEX_FILE=%TEMP%\.tmp.index
    git read-tree HEAD:_Folder2
    git checkout-index -f -a --prefix=c:\MyRepo\
    set GIT_INDEX_FILE=
    del %TEMP%\.tmp.index
    

    I'm not familiar with Windows CMD, so I'm not sure if the 2 set commands are proper.