Can you change a file content during git commit? Can you change a file content during git commit? git git

Can you change a file content during git commit?


The actual commit stuck in by git commit is whatever is in the index once the pre-commit hook finishes. This means that you can change files in the pre-commit hook, as long as you git add them too.

Here's my example pre-commit hook, modified from the .sample:

#!/bin/sh## An example hook script to verify what is about to be committed.# [snipped much of what used to be in it, added this --#  make sure you take out the exec of git diff-index!]num=$(cat zorg)num=$(expr 0$num + 1)echo $num > zorggit add zorgecho "updated zorg to $num"exit 0

and then:

$ git commit -m dinkupdated zorg to 3[master 76eeefc] dink 1 file changed, 1 insertion(+), 1 deletion(-)

But note a minor flaw (won't apply to your case):

$ git commitgit commitupdated zorg to 4# On branch master# Untracked files:[snip]nothing added to commit but untracked files present (use "git add" to track)$ git commitupdated zorg to 5# Please enter the commit message for your changes. Lines starting[snip - I quit editor without changing anything]Aborting commit due to empty commit message.$ git commitupdated zorg to 6# Please enter the commit message for your changes. Lines starting

Basically, because the pre-commit hook updates and git adds, the file keeps incrementing even though I'm not actually doing the commit, here.

[Edit Aug 2021: I need to emphasize that I do not recommend this approach. Note that there are some oddball cases that can come up when using git commit -a, git commit --include, and git commit --only, including the implied --only that is inserted if you name files on the command line. This is due to the fact that this kind of git commit creates a second, and sometimes even a third, internal Git index. Any git add operations you do inside a hook can only affect one of these two or three index files.]


It turns out you can run "hooks" - they are actually handled by another mechanism - when staging files (at git add time) :

https://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes#_keyword_expansion

(scroll down a bit to the "smudge" and "clean" diagrams)

Here is what I understood :

  1. edit the .gitattributes, and create rules for the files which should trigger a dictionary update:

    novel.txt filter=updateDict

  2. Then, tell Git what the updateDict filter does on smudge (git checkout) and clean (git add):

    $ git config --global filter.updateDict.clean countWords.script

    $ git config --global filter.updateDict.smudge cat