Search code examples
gitgithubversion-controlgit-brancharchive

Any way to turn all git branches into folders for a repository?


I have several branches in a git repo.

-repo
  -- branch1
  -- branch2

For some reason I need to move the repo into another repo without histories. As branch1 and branch2 differs in code so it would be helpful for me If I can automatically create branch to folder map inside repo in the new location. Is there any way to do so?

Actual problem is I have single git repo called archives in GitHub inside which I need to keep several repo with browse-able source code. What are other options available in my hand?


Solution

  • I'm not sure if a solution using only git might exist since it's not quite the purpose of the tool. However, the basic command exist on top of which you could build your own script.

    You'll need:

    1. to list the branch on your remote: git ls-remote --heads origin
    2. clone only a branch by its name: git clone -b BRANCH_NAME --single-branch REMOTE_URL DESTINATION

    Using this two command, you can automate the process in bash like so:

    #!/usr/bin/env bash
    
    ####
    #
    # $1 = Remote URL to be clonned
    # $2 = New name of the repository
    #
    ####
    
    remote=$1
    repository=$2
    workdir=$(pwd)
    destination="$workdir/$repository"
    
    echo "Creating repository at $destination"
    mkdir "$destination"
    
    git clone "$remote" "$repository"
    cd "$repository"
    
    for branch in $(git ls-remote --heads origin | grep -o "refs/heads/.*$" | cut -d / -f 3-)
    do
            echo "Cloning into branch $branch"
            git clone -b $branch --single-branch $remote "$destination/$branch"
    done
    
    echo "Current dir: $(pwd)"
    echo "Deleting all .git and .gitignore files"
    
    rm -rf "$destination"/*/.gitignore
    rm -rf "$destination"/*/.git
    rm -rf "$destination"/.gitignore
    rm -rf "$destination"/.git
    
    cd $workdir
    
    echo "All done! cur dir: $(pwd)"
    

    Save this piece of code inside a file like my-repo-cloner.sh, and you can clone your repo (with the structure you want) using ./my-repo-cloner.sh REMOTE_URL MYREPO