简体   繁体   中英

Is there a way to git add a file during a pre-commit hook?

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?

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 excessing 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM