1

我想在提交之前使用 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

提前感谢您的帮助

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

4

1 回答 1

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
于 2019-05-16T11:22:21.097 回答