Clone a subdirectory from github using git

207 Views Asked by At

In git I want to download a folder from a Github repository and add it to a subdirectory in my repo like so:

repo/folder/subfolder/

repo/folder/subfolder/clonedfolder //cloned folder from git hub

But I get the path directories as well which I don't want.

repo/folder/subfolder/folder/folder1/folder2/clonedfolder

This what I have tried

repo/folder/subfolder$ git init

repo/folder/subfolder$ git remote add -f origin [email protected]:repo/repo.git

repo/folder/subfolder$ git sparse-checkout init

repo/folder/subfolder$ git sparse-checkout set clonedfolder

repo/folder/subfolder$ git sparse-checkout list
- clonedfolder

repo/folder/subfolder$ git pull origin develop

Is this possible in git?

1

There are 1 best solutions below

0
amphetamachine On

Git isn't geared toward this. Reason being, that whenever you fetch from a repo, your .git/objects folder contains all changes to all files in the repo.*

If you have a choice, I'd separate concerns into Git submodules, which are more-or-less independent git repositories linked together using a parent project (with a .gitmodules file).

Then you can just use symbolic links to make the directory structure you want.

For example:

mkdir parent-project ; cd parent-project
git init
mkdir .my-git-root-folders
git submodule add https://example.com/child.git .my-git-root-folders/child
ln -s .my-git-root-folders/child/path/to/subfolder childmodule
git add childmodule
git commit -m 'Add and link child module'

After this you can access childmodule/some-file as if you were accessing <child repo>/path/to/subfolder/some-file.☥

Git will track symbolic links.‡

Footnotes:

  • * Except in cases of shallow clones, which only include the latest revisions for each reachable HEAD. Each file's state is still recorded, however.
  • If your code doesn't specifically test for symbolic links.
  • Windows is known to have problems with symbolic links; you need Administrator access to even create them. For best results, use either Linux, Mac OSX, Windows WSL, or a Linux virtual machine.