Question

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?

Was it helpful?

Solution 2

I think you need to do git diff against what is about to be committed by using --cached:

FICHEROS=`git diff --cached --name-only`

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top