Search code examples
bashlaravelgithookslaravel-artisan

Create simple auto deploy using git hooks + laravel artisan command


Im trying to make a simple auto deploy using git hooks post-receive and i found this link.That link gave me idea and modified it myself. It is working well when the BRANCH Variable is "master". but when i am changing it to other branch, let say "phase2", it always stays in "master" branch when the time of running the artisan commands. So my cache route came from master branch.

This is my post-receive hook file :

#!/bin/sh
TARGET="/usr/local/apache2/htdocs/project_uat"
GIT_DIR="/home/user0001/www/project_name/.git"

BRANCH="phase2" # I want this changable to phase3,phase4 or what ever branch

while read oldrev newrev ref
do
        # only checking out the master (or whatever branch you would like to deploy)
        if [[ $ref = "refs/heads/${BRANCH}" ]];
        then
                echo "Ref $ref received. Deploying ${BRANCH} branch to UAT..."
                git --work-tree=$TARGET --git-dir=$GIT_DIR checkout -f
        else
                echo "Ref $ref received. Doing nothing: only the ${BRANCH} branch may be deployed on this server."
        fi
done

cd /usr/local/apache2/htdocs/project_uat
php artisan cache:clear
php artisan config:cache
php artisan route:cache
php artisan optimize

When i try to navigate to my target dir. It stays in phase2 branch but theres is a lot of changes when i try to "git status". These changes came from master.

Basically, all i wanted is to automate the deployment everytime i "git push" from my local without logging in to remote server just to run the following commands:

  • cd to/project/path
  • git pull origin phase2
  • php artisan cache:clear
  • php artisan config:cache
  • php artisan route:cache
  • php artisan optimize

And the only think i can make it is trough GIT HOOKS


Solution

  • After struggling a lot and with the help of @VonC

    I finalize my hook as simple as:

    #!/bin/sh
    unset $(git rev-parse --local-env-vars)
    cd /usr/local/apache2/htdocs/project_uat
    
    env -i git reset --hard
    env -i git clean -f -d
    env -i git pull
    php artisan cache:clear
    php artisan config:cache
    php artisan route:cache
    php artisan optimize
    

    I don`t know the downside yet.