GIt preCommit (maybe with help PhpStorm) and php-c

2019-07-23 04:20发布

I want automatic process, when I commit file my php-cs-fixer trn and fix all files which add to commit, maybe PhpStorm have some opportunity, running external tools before commit or push. I found only after commit, but I don't need after, need before. And I try tune my git, using pre-commit event I create in my project file, like example, just without extension

sudo gedit .git/hooks/pre-commit

then add code

#!/usr/bin/env bash

ROOT="/home/ivan/host/master"

echo "php-cs-fixer pre commit hook start"

PHP_CS_FIXER="php-cs-fixer"
HAS_PHP_CS_FIXER=false

if [ -x php-cs-fixer ]; then
    HAS_PHP_CS_FIXER=true
fi

if $HAS_PHP_CS_FIXER; then
    git status --porcelain | grep -e '^[AM]\(.*\).php$' | cut -c 3- | while read line; do
        $PHP_CS_FIXER fix --config-file=$ROOT/.php_cs --verbose "$line";
        git add "$line";
    done
else
    echo ""
    echo "Please install php-cs-fixer, e.g.:"
    echo ""
    echo "  composer require --dev fabpot/php-cs-fixer:dev-master"
    echo ""
fi

echo "php-cs-fixer pre commit hook finish"

then compare when I running php-cs-fixer for some file,

php-cs-fixer fix src/AppBundle/Services/OutboundInvoiceService.php

then checking file and have many fixer part for this file, then checkout changes and just add empty line for this file and commit it, pre-commit not working, only what I have in my repo commit with empty line, without php-cs-fixer working. What am I doing wrong ?

Example where I add unused namespaces, php-cs-fixer must remove it and add some another fix, but after add file I have only unused namespace :(

enter image description hereenter image description here enter image description here enter image description here enter image description here

Only working if I create php file

#!/usr/bin/php
<?php
/**
 * .git/hooks/pre-commit
 *
 */

 /**
  * collect all files which have been added, copied or
  * modified and store them in an array called output
  */
 exec('git diff --cached --name-status --diff-filter=ACM', $output);
foreach ($output as $file) {

$fileName = trim(substr($file, 1) );
/**
 * Only PHP file
 */
if (pathinfo($fileName,PATHINFO_EXTENSION) == "php") {
    /**
     * Check for error
     */
    $lint_output = array();
    exec("php -l " . escapeshellarg($fileName), $lint_output, $return);
    if ($return == 0) {

        /**
         * PHP-CS-Fixer && add it back
         */
        exec("php-cs-fixer fix {$fileName}; git add {$fileName}");
    } else {

        echo implode("\n", $lint_output), "\n";

        exit(1);

    }
    }
}
exit(0);

and after git add file before pushed, run this file.

But this is complicated approach, because after commit file, I need run this script, BUT IT'S WORKING.

And my question how to use git hooks pre-commit for automatic this process ?

0条回答
登录 后发表回答