How to run composer install only if composer.json and composer.lock are are changed

If you are a developer, system engineer, or DevOps engineer who works with PHP projects, you know that running composer install is an important task. However, when it comes to continuous integration and continuous deployment (CI/CD), running composer install every time can be time-consuming and unnecessary if the composer files haven’t changed.

In this post, I want to share a little trick on how we can automatically run Composer only when the composer.json and composer.lock files have been changed.

Requirements:

  • Server: Ubuntu 20.04
  • Language: PHP8
  • Project path: /data/repo/example-project (is stored on GitHub and cloned to this directory on a server)

NOTED: Before we start creating this script, please note that I’m using "root" user, and have configured SSH Credentials under "root" user for authentication with GitHub. Most of the files are under /root/.ssh/. That’s why we’re not using sudo command here.

1. Create a script

Create a script called /usr/local/bin/git-update.sh with the content below:

#!/bin/bash

git pull -q --ff-only

if [[ -f composer.phar ]]; then
    repoName=${PWD##*/} # Get current folder name
    checkFile=/tmp/composer_hash_${repoName}.sha12
    if [[ ! -f $checkFile || $(sha1sum -c ${checkFile} 2> /dev/null | grep FAILED | awk "{print \$2}") == *"FAILED"* ]]; then
        php composer.phar --ignore-platform-reqs --no-dev install
        retVal=$?
        if [[ $retVal -eq 0 ]]; then
            sha1sum composer.json composer.lock > ${checkFile}
        fi
    fi
fi

Noted: the example project has composer.phar file inside, you can use composer command if you have made it into a global command.

Grant permission for the script, we just want root user run this script, so a 700 permission is enough:

chmod 700 /usr/local/bin/git-update.sh

2. Create a crontab job

In /etc/cron.d, we create a cron task job called git-update-example-project by

cd /etc/cron.d
touch git-update-example-project
nano git-update-example-project

Then add the content below

# Job Definition
*/5 * * * *  root  cd /data/repo/git-update-example-project && /usr/local/bin/git-update.sh

That’s all we need, for now, when we make changes to our projects locally on your laptop, and later you push these changes to the remote repository on GitHub where your code project is stored. The code projects hosted on your server will be automatically updated every 5 minutes and also run composer install without running the command manually.


Discover more from Turn DevOps Easier

Subscribe to get the latest posts sent to your email.

By Binh

Leave a Reply

Your email address will not be published. Required fields are marked *

Content on this page