【问题标题】:PHP-CS-Fixer fix in precommit hook but file doesn't add to commitPHP-CS-Fixer 修复了 precommit 钩子,但文件未添加到提交
【发布时间】:2018-03-04 23:22:28
【问题描述】:

我想在提交之前使用 php-cs-fixer 自动修复文件,然后提交包括这些修复在内的更改

所以我创建了预提交文件,但是我遇到了问题:

1) 我不知道哪个文件被更改(可能只是 bash 问题)

2)如果我无条件运行“git add”,则包含更改以提交,但不包含文件本身

我试图在钩子的 cmets 中清楚地显示它,所以它是:

#!/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

提前感谢您的帮助

我特别想知道correction_code为什么没有价值以及为什么 “git add”之后的文件具有相同的内容,但无论如何都没有提交

【问题讨论】:

标签: php git bash pre-commit php-cs-fixer


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-28
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    • 2017-04-29
    相关资源
    最近更新 更多