Исправление PHP-CS-Fixer в хуке precommit, но файл не добавляет коммит

Я хочу автоматически исправить файлы с помощью php-cs-fixer перед фиксацией, а затем зафиксировать изменения, включая эти исправления

Итак, я создал файл предварительной фиксации, но у меня есть проблемы:

1) Я не могу узнать, какой файл был изменен (возможно, просто проблема с bash)

2) Если я запускаю "git add" без условий, изменения включаются в коммит, но не в сами файлы

Я попытался ясно показать это в комментариях о хуке, так что вот оно:

#!/usr/bin/env bash 

# get the list of changed files
staged_files=$(git diff --cached --name-only)

# command to fix files
cmd='vendor/bin/php-cs-fixer fix %s -q'
if [ -f 'php_cs_fixer_rules.php' ]; then
    cmd='vendor/bin/php-cs-fixer fix %s -q --config=php_cs_fixer_rules.php'
fi

for staged in ${staged_files}; do # this cycle exactly works
    # work only with existing files
    if [[ -f ${staged} && ${staged} == *.php ]]; then # this condition exactly works
        # use php-cs-fixer and get flag of correction
        eval '$(printf "$cmd" "$staged")' # this command exactly works and corrects the file
        correction_code=$? # but this doesn't work

        # if fixer fixed the file
        if [[ ${correction_code} -eq 1 ]]; then #accordingly this condition never works
            $(git add "$staged") # even if the code goes here, then all changes will go into the commit, but the file itself will still be listed as an altered
        fi
    fi
done

exit 0 # do commit

Заранее благодарю за любую помощь

Особенно я хочу знать, почему коррекционный код не получает значения и почему файлы после "git add" имеют идентичный контент, но все равно не зафиксированы

0 ответов

В pre-commit, если вы добавите несколько файлов git add, эти файлы появятся в файлах для фиксации.

Проблема в вашем pre-commit является [[ ${correction_code} -eq 1 ]].

когда php-cs-fixer fix успешно, он возвращает 0, а не 1.


Так что pre-commit должно быть:

#!/usr/bin/env bash 

# get the list of changed files
staged_files=$(git diff --cached --name-only)

# build command to fix files
cmd='vendor/bin/php-cs-fixer fix %s -q'
if [ -f 'php_cs_fixer_rules.php' ]; then
    cmd='vendor/bin/php-cs-fixer fix %s -q --config=php_cs_fixer_rules.php'
fi

for staged in ${staged_files}; do
    # work only with existing files
    if [[ -f ${staged} && ${staged} == *.php ]]; then
        # use php-cs-fixer and get flag of correction
        "$cmd" "$staged" // execute php-cs-fixer directly
        correction_code=$? # if php-cs-fixer fix works, it returns 0

        # HERE, if returns 0, add stage it again
        if [[ ${correction_code} -eq 0 ]]; then
            git add "$staged" # execute git add directly
        fi
    fi
done

exit 0 # do commit
Другие вопросы по тегам