Get the list of unstaged files in git pre-commit hook

818 views Asked by At


I've spent a whole lot of time on stackoverflow/google trying to figure out a solution for this problem. May be the solution is simple and I am missing something.

So I have a pre-commit hook(shell script) which runs few tests on committed files. If a committed file fails a test, it is removed from the stage. I want to printout all the unstated files from inside the script. Here's what I have tried so far from inside the script.

  1. git diff --name-only --diff-filter=M
  2. git ls-files -m
  3. git diff --name-only

All of them throw the same error as shown below:

fatal: This operation must be run in a work tree

P.S. I am running this inside .git folder(since hooks reside there) and hence the error.

Any suggestions would be really helpful.

2

There are 2 answers

0
Gautam On BEST ANSWER

I asked a colleague of mine and he came up with a solution specifically for shell script. Sometimes you just have to think simple!

Just change the directory using "cd" and run the command once you are outside the .git folder.

0
Muayyad Alsadi On

add the following at the top of your script assuming your hook .git/hooks/

#! /bin/bash
here=`dirname "$0"`
cd "$here/../.."