Skip to content

Instantly share code, notes, and snippets.

@elminson
Created September 7, 2023 00:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elminson/45d47e35dbf2b1bfd32eb15dd129748b to your computer and use it in GitHub Desktop.
Save elminson/45d47e35dbf2b1bfd32eb15dd129748b to your computer and use it in GitHub Desktop.

Step 1

create hooks/pre-commit file with this content

#!/bin/bash

# Get the current branch name
current_branch=$(git rev-parse --abbrev-ref HEAD)

# Skip execution if the branch is 'beta' or 'dev'
if [[ $current_branch == "master" ]] || [[ $current_branch == "beta" ]] || [[ $current_branch == "dev" ]]; then
    echo "Skipping script execution for branch $current_branch."
    exit 0
fi

# Get the list of modified files by git
modified_files=$(git diff --name-only --cached)

# Initialize a variable to check if any CSS file is found
css_found=0

# Loop through the modified files and check for 'css' extension
for file in $modified_files; do
    if [[ $file == *.css ]]; then
        css_found=1
        break
    fi
done

# If any file has the 'css' extension, execute the specified commands
if [[ $css_found -eq 1 ]]; then
    current_hash=$(git log --pretty="%h" -n1 HEAD)

    # Check if css_version file exists and read its content
    if [[ -f css_version ]]; then
        stored_hash=$(cat css_version)
    else
        stored_hash=""
    fi

    # Only commit if the current hash and stored hash are different
    if [[ $current_hash != $stored_hash ]]; then

        echo $current_hash > css_version
        git update-index --add css_version
        git checkout --theirs css_version
        git add css_version
        echo "CSS version updated to $current_hash."
    else
        echo "CSS version is already up-to-date."
    fi
else
    echo "No CSS files found."
fi

Step 2

Add this in your composer.json

"scripts": {
        "post-install-cmd": [
            "cp -r 'hooks/' '.git/hooks/'",
            "php -r \"copy('hooks/pre-commit', '.git/hooks/pre-commit');\"",
            "php -r \"chmod('.git/hooks/pre-commit', 0777);\""
        ]
    }

Step 3

execute

composer run post-install-cmd

This command will install the pre-commit file on .git folder

Step 4

in your core html template load the version

<?php
$cssVersion = file_get_contents("css_version");
?>
#implementation in all your css link href
<link href="<?=base_url();?>css/app.css?v=<?=$cssVersion?>" rel="stylesheet">
<link href="<?=base_url();?>css/morestyles.css?v=<?=$cssVersion?>" rel="stylesheet">
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment