我正在编写一个简单的Git pre-commit钩子,在将要提交的文件中运行Astyle(一种代码美化工具)。以下是代码:
#!/bin/sh
echo "git diff:"
FICHEROS=`git diff --name-only`
if [ -z "${FICHEROS}" ]; then
echo "Files not found"
else
echo "files are:"
echo "$FICHEROS"
cp $FICHEROS ${FICHEROS}_copy
echo "Running astyle"
/home/robgon/astyle/build/gcc/bin/astyle --indent=force-tab --pad-oper --pad-paren --delete-empty-lines --suffix=none --indent-namespaces --indent-col1-comments -n ${FICHEROS}_copy
echo "Formatted"
fi
当我尝试使用git commit -a -m "test1"提交一个名为"file1.c"的文件时,控制台会显示以下内容:
git diff:
Files not found
[master d3d2526] test1
1 file changed, 1 insertion(+), 1 deletion(-)
因此,git diff --name-only没有将输出设置为FICHEROS。如果pre-commit只尝试运行astyle,则脚本将跳过输出并且不会格式化文件...
如果我从控制台运行.git/hooks/pre-commit,我会得到:
git diff:
files are:
file1.c
Running astyle
Formato /home/robgon/gitTuto/gitRepo1/proj/file1.c_copy
Formatted
为什么Git无法在pre-commit脚本中执行astyle和设置变量,但是当我从控制台运行pre-commit时,它可以正常工作?
git status
会发生什么? - John Zwinck