1

I'm trying to create a precommit hook to prevent committing merge conflicts accidentally... basically cancelling the commit when it includes >>>>. I've found multiple viable-looking approaches, but I am wondering why the "official" approach is not working (trying to use https://stackoverflow.com/a/27150330/752916 which refers to https://github.com/git/git/blob/v2.26.0/templates/hooks--pre-commit.sample#L49). When I execute this command, I am presented with usage information (see below) instead of an error. I expected something like this leftover conflict marker because I have a test conflict in my codebase. I am not looking for alternatives, those are readily available on SO already. I just want to know why this command doesn't work.

$ git diff-index --check --cached $against --
usage: git diff-index [-m] [--cached] [<common-diff-options>] <tree-ish> [<path>...]
common diff options:
  -z            output diff-raw with lines terminated with NUL.
  -p            output patch format.

Debugging info:

$ git --version
git version 2.25.0.windows.1

I tried this in Git Bash and Windows Powershell, same result in both.

Community
  • 1
  • 1
AlexMA
  • 9,842
  • 7
  • 42
  • 64
  • What does `$against` expand to here? – torek Apr 07 '20 at 20:14
  • @torek $against appears to be an empty string. `echo "Against is $against"` in my githook outputs `Against is ` – AlexMA Apr 07 '20 at 20:18
  • OK, that would be the problem then: `git diff-index` *requires* a `` argument, as indicated by the syntax. Which tree would you like to diff the index against? – torek Apr 07 '20 at 20:31
  • Yes and no. Yes, $against needs to be a tree-ish. But, I don't believe I am required to set that value myself - git should do it for me. If git on windows has the restriction that `$against` is not available, then is a git hook with this command impossible on Windows despite it being the official example? Or does it just involve an extra step of setting $against to the right tree-ish? If so, what should the right tree-ish be? – AlexMA Apr 07 '20 at 20:37
  • Did you copy the entire script from `https://github.com/git/git/blob/v2.26.0/templates/hooks--pre-commit.sample`? `against` is set at line 12 or line 15, depending on other conditions. If you copied only line 47, `against`—which is a *shell* variable, not a Git one—is not going to be set. – torek Apr 07 '20 at 21:35
  • @torek Oh wow, you're totally right. I am blind. If you copy that to the answer I will give you the green check. – AlexMA Apr 07 '20 at 21:38

1 Answers1

2

As per comments, the basic issue here was copying some, but not enough, of the script at https://github.com/git/git/blob/v2.26.0/templates/hooks--pre-commit.sample. With shell variable against unset, $against expanded to nothing at all, leaving git diff-index with no <tree-ish> argument.

Copying enough setup from the script should fix the problem.

torek
  • 448,244
  • 59
  • 642
  • 775