Git: How do I clone a subdirectory only of a Git repository?

前端 未结 18 2900
时光说笑
时光说笑 2020-11-21 04:33

I have my Git repository which, at the root, has two sub directories:

/finisht
/static

When this was in SVN, /finisht was chec

18条回答
  •  爱一瞬间的悲伤
    2020-11-21 05:06

    It's not possible to clone subdirectory only with Git, but below are few workarounds.

    Filter branch

    You may want to rewrite the repository to look as if trunk/public_html/ had been its project root, and discard all other history (using filter-branch), try on already checkout branch:

    git filter-branch --subdirectory-filter trunk/public_html -- --all
    

    Notes: The -- that separates filter-branch options from revision options, and the --all to rewrite all branches and tags. All information including original commit times or merge information will be preserved. This command honors .git/info/grafts file and refs in the refs/replace/ namespace, so if you have any grafts or replacement refs defined, running this command will make them permanent.

    Warning! The rewritten history will have different object names for all the objects and will not converge with the original branch. You will not be able to easily push and distribute the rewritten branch on top of the original branch. Please do not use this command if you do not know the full implications, and avoid using it anyway, if a simple single commit would suffice to fix your problem.


    Sparse checkout

    Here are simple steps with sparse checkout approach which will populate the working directory sparsely, so you can tell Git which folder(s) or file(s) in the working directory are worth checking out.

    1. Clone repository as usual (--no-checkout is optional):

      git clone --no-checkout git@foo/bar.git
      cd bar
      

      You may skip this step, if you've your repository already cloned.

      Hint: For large repos, consider shallow clone (--depth 1) to checkout only latest revision or/and --single-branch only.

    2. Enable sparseCheckout option:

      git config core.sparseCheckout true
      
    3. Specify folder(s) for sparse checkout (without space at the end):

      echo "trunk/public_html/*"> .git/info/sparse-checkout
      

      or edit .git/info/sparse-checkout.

    4. Checkout the branch (e.g. master):

      git checkout master
      

    Now you should have selected folders in your current directory.

    You may consider symbolic links if you've too many levels of directories or filtering branch instead.


提交回复
热议问题