Git - separate folder for each branch. Setting it up

前端 未结 4 1741
鱼传尺愫
鱼传尺愫 2021-02-01 10:08

I have a need to keep 3 branches in 3 separate folders. (I know this is not a git way of doing things. But I need to do this for a reason).

Lets say the repo name is

4条回答
  •  情话喂你
    2021-02-01 10:37

    Here's a bash script to check out all remote branches into separate worktrees and then keep them in sync. Every time it runs it will throw away any local changes. It just tries to make the checked out code mirror the repo.

    git fetch --all --prune
    
    # reset branch only if it has deviated from the remote
    function update_branch {
            if git diff --exit-code --quiet $1; then
                    echo "No changes on branch $1"
            else
                    echo "Resetting branch $1"
                    git reset --hard $1
            fi
    }
    
    # master branch is checked out in the root
    update_branch origin/master
    
    # check out each remote branch into a subfolder
    branches=$(git for-each-ref --format='%(refname:short)' refs/remotes/origin | grep -v /HEAD | grep -v /master)
    for branch in $branches; do
            if [ -d $branch ]; then
                    cd $branch
                    update_branch $branch
                    cd $OLDPWD
            else
                    echo "Checking out new branch $branch"
                    git worktree add $branch $branch
            fi
    done
    
    # check for branches that have been deleted on the remote
    for branch in origin/*; do
            if ! git show-ref --verify refs/remotes/$branch --quiet; then
                    echo "Removing worktree $branch"
                    git worktree remove $branch
            fi
    done
    
    git worktree prune
    
    

提交回复
热议问题