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

前端 未结 18 2883
时光说笑
时光说笑 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:11

    I wrote a .gitconfig [alias] for performing a "sparse checkout". Check it out (no pun intended):

    On Windows run in cmd.exe

    git config --global alias.sparse-checkout "!f(){ [ $# -eq 2 ] && L=${1##*/} L=${L%.git} || L=$2; mkdir -p \"$L/.git/info\" && cd \"$L\" && git init --template= && git remote add origin \"$1\" && git config core.sparseCheckout 1; [ $# -eq 2 ] && echo \"$2\" >> .git/info/sparse-checkout || { shift 2; for i; do echo $i >> .git/info/sparse-checkout; done }; git pull --depth 1 origin master;};f"
    

    Otherwise:

    git config --global alias.sparse-checkout '!f(){ [ $# -eq 2 ] && L=${1##*/} L=${L%.git} || L=$2; mkdir -p "$L/.git/info" && cd "$L" && git init --template= && git remote add origin "$1" && git config core.sparseCheckout 1; [ $# -eq 2 ] && echo "$2" >> .git/info/sparse-checkout || { shift 2; for i; do echo $i >> .git/info/sparse-checkout; done }; git pull --depth 1 origin master;};f'
    

    Usage:

    # Makes a directory ForStackExchange with Plug checked out
    git sparse-checkout https://github.com/YenForYang/ForStackExchange Plug
    
    # To do more than 1 directory, you have to specify the local directory:
    git sparse-checkout https://github.com/YenForYang/ForStackExchange ForStackExchange Plug Folder
    

    The git config commands are 'minified' for convenience and storage, but here is the alias expanded:

    # Note the --template= is for disabling templates.
    # Feel free to remove it if you don't have issues with them (like I did)
    # `mkdir` makes the .git/info directory ahead of time, as I've found it missing sometimes for some reason
    f(){
        [ "$#" -eq 2 ] && L="${1##*/}" L=${L%.git} || L=$2;
        mkdir -p "$L/.git/info"
            && cd "$L"
            && git init --template=
            && git remote add origin "$1"
            && git config core.sparseCheckout 1;
        [ "$#" -eq 2 ]
            && echo "$2" >> .git/info/sparse-checkout
            || {
                shift 2;
                for i; do
                    echo $i >> .git/info/sparse-checkout;
                done
            };
        git pull --depth 1 origin master;
    };
    f
    

提交回复
热议问题