Whether it is a good practise or not, some people might need it so this example automatically runs a bash script after composer install in a symfony application. The bash script then creates an executable GIT pre-push hook under ".git/git-hooks" folder.


Composer.json


{
},
"scripts": {
....,
"post-install-cmd": [
....
"chmod +x composer/git-pre-push.sh && composer/git-pre-push.sh"
],
....
}
}

git-pre-push.sh


#!/usr/bin/env bash


createFile()
{
cat << EOF > $1
#!/bin/sh

if [ -f ./bin/php-cs-fixer ]
then
./bin/php-cs-fixer fix --dry-run --quiet src
if [ \$? -ne 0 ]
then
RED="\033[0;31m"
CYAN="\033[0;36m"
NONE="\033[0m"

printf "\n\t\${CYAN}[GIT POLICY]\${NONE} PHP-CS-Fixer has failed - \${RED}Push Aborted\${NONE}\n\n"

return 1
fi
fi
EOF
}

makeFileExecutable()
{
chmod +x $1 2>/dev/null
# If successfully made the file executable
if [ $? -eq 0 ];
then
printf " ${GREEN}${CHECK} Successfully made GIT \"$GIT_HOOK_FILE\" hook executable.${NONE}\n\n"
# If failed to make the file executable
else
printf " ${RED}${CROSS} Failed to make GIT \"$GIT_HOOK_FILE\" hook executable.${NONE}\n\n"
fi
}


GIT_HOOK_DIR=".git/hooks"
GIT_HOOK_FILE="pre-push"
NONE="\033[0m"
CYAN="\033[0;36m"
RED="\033[0;31m"
GREEN="\033[0;32m"
CROSS="\u2718"
CHECK="\u2714"


printf "\n ${CYAN}[COMPOSER SCRIPT]${NONE}\n"
printf " -----------------\n"

# If the directory doesn't exists
if [ ! -d "$GIT_HOOK_DIR" ];
then
printf " ${RED}${CROSS} Directory \"$GIT_HOOK_DIR\" doesn't exist so ignoring the script.${NONE}\n\n"
# If the directory exists
else
# If the file exists
if [ -f "$GIT_HOOK_DIR/$GIT_HOOK_FILE" ];
then
# If the file executable
if [ -x "$GIT_HOOK_DIR/$GIT_HOOK_FILE" ];
then
printf " ${GREEN}${CHECK} Executable GIT \"$GIT_HOOK_FILE\" hook already exists.${NONE}\n\n"
# If the file isn't executable
else
printf " ${RED}${CROSS} GIT \"$GIT_HOOK_FILE\" hook already exists but not executable.${NONE}\n"

makeFileExecutable "$GIT_HOOK_DIR/$GIT_HOOK_FILE"
fi
# If the file doesn't exist
else
createFile 2>/dev/null "$GIT_HOOK_DIR/$GIT_HOOK_FILE"
# If successfully created the file
if [ $? -eq 0 ];
then
printf " ${GREEN}${CHECK} Successfully created GIT \"$GIT_HOOK_FILE\" hook.${NONE}\n"

makeFileExecutable "$GIT_HOOK_DIR/$GIT_HOOK_FILE"
# If failed to create the file
else
printf " ${RED}${CROSS} Failed to create GIT \"$GIT_HOOK_FILE\" hook.${NONE}\n\n"
fi
fi
fi

pre-push


When user runs git push ...., this script check PSR code standards behind scene and either terminates the process or carries on.


#!/bin/sh

if [ -f ./bin/php-cs-fixer ]
then
./bin/php-cs-fixer fix --dry-run --quiet src
if [ $? -ne 0 ]
then
RED="\033[0;31m"
CYAN="\033[0;36m"
NA="\033[0m"

printf "\n\t${CYAN}[GIT POLICY]${NA} PHP-CS-Fixer has failed - ${RED}Push Aborted${NA}\n\n"

return 1
fi
fi