During our pre-commit hook, I've added an additional command to run that could result in a modified or new file if certain other changes have taken place. I'm curious if it's possible that I add this file in the changes to be committed during this pre-commit hook? I've tried some naieve approaches, such as just calling the literal 'git add fileName' after the command in the pre-commit hook, but it doesn't seem to work. Is this even possbiel to do?
-
Does this answer your question? [Can a Git hook automatically add files to the commit?](https://stackoverflow.com/questions/3284292/can-a-git-hook-automatically-add-files-to-the-commit) – Inigo Dec 16 '22 at 11:01
1 Answers
It looks like there are some workarounds as found in this issue which suggests using git add -u
for existing files; however, changing the source code or even just configuration files is likely not a great idea since it is possible for your commit hook to silently introduce a new bug or unexpected behavior.
You could mitigate this by running a linter, static code analysis, run tests, or recompile affected source at each commit and fail the commit if any of those report a new error, but that will obviously introduce a lot of excess computing time for each commit and would take time to implement so this is also probably not a good idea.
I would suggest having the pre-commit detect when a file needs to be modified or created and notify the user, while specifying what commands or scripts need to be run to properly prepare the staged changes for the commit. While adding one or more manual steps to the process, this will give you an opportunity to run any necessary checks on version numbers, code style, compilation errors, etc.

- 3,001
- 2
- 10
- 24
-
I actually like this idea. Just notify the user if the file in mind has been altered, and let them know they need to test it out and add it. – kastaplastislife Nov 15 '21 at 15:14
-