Reputation: 107
IM writting a simple git pre-commit hook to run Astyle (a code beautifier) in the files that are going to be commited. Here is the code:
#!/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
When I try to commit a file, named "file1.c" with a git commit -a -m "test1", for example, I get in the console:
git diff:
Files not found
[master d3d2526] test1
1 file changed, 1 insertion(+), 1 deletion(-)
So, the git diff --name-only is not setting the output in FICHEROS. If the pre-commit only try to run astyle, the script skips the output and doesnt format the file...
If i run the .git/hooks/pre-commit from my console I get:
git diff:
files are:
file1.c
Running astyle
Formato /home/robgon/gitTuto/gitRepo1/proj/file1.c_copy
Formatted
Why git cant execute astyle and set variables in the pre-commit script, and when i run the pre-commit from my console, it works?
Upvotes: 4
Views: 1619
Reputation: 107
Here is the new script, it runs now:
!/bin/sh
echo `git status`
echo "git diff:"
FICHEROS=`git diff --cached --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
Upvotes: 2
Reputation: 249642
I think you need to do git diff
against what is about to be committed by using --cached
:
FICHEROS=`git diff --cached --name-only`
Upvotes: 1