One Branch Per Git Repo

One Branch Per Git Repo

Installing LEMP

On a clean install of Ubuntu 18.04.2:

sudo apt update
sudo apt install nginx
sudo apt install mariadb-server
sudo mysql -u root

use mysql;
update user set plugin=” where User=’root’;
flush privileges;
\q

mysql_secure_installation
sudo apt install php-fpm php-mysql
sudo apt install php7.2-xml php7.2-mbstring

Editing Nginx Config

server {
    server_name ~^(?<branch>.*)\.staging\.mydomain\.com$;
    access_log /var/log/nginx/branch-access.log;
    error_log /var/log/nginx/branch-error.log;
    index index.php index.html;
    root /git/branches/$branch;
}

Note that if you’re using Laravel, change the root to read /git/branches/$branch/public

Cloning the Branch

cd ~/git

git clone https://gitlab.com/username/project

nano gitbranch.sh

 

gitbranch.sh

# Fetch the latest branches
git fetch

# Get the repository path
repoPath=`git config --get remote.origin.url`

# Loop through each branch
for branches in $(git for-each-ref --format='%(refname)' refs/remotes/)
do
        # Remove redundant string from branch name
        myBranch=${branches/refs\/remotes\/origin\//}

        # Check if we are using 'HEAD' branch
        if [ "$myBranch" == "HEAD" ]
        then
                continue
        fi

        # Check if the branch has already been checked out
        if [ -e /git/branches/"$myBranch" ]
        then
                # Switch to the branch directory
                cd /git/branches/"$myBranch"

                # Pull latest code
                status=`git pull`

                # Check if there are any changes
                if [ "$status" == "Already up-to-date." ]
                then
                    continue
                else
                    continue
                fi
        else
            # Switch to branches directory
            cd /git/branches/

            # Clone repository to branch named directory
            git clone $repoPath "$myBranch"

            # Switch to specific branch directory
            cd /git/branches/"$myBranch"

            # Switch to the branch
            git checkout $myBranch

        fi
done