sdbol sdbol - 1 year ago 86
Git Question

Git and updating a file's contents when merging

I have a git repository that contains code written in C. One of the files is a Version.c file which contains the line

#define Version_Build "0"

I have a script that can find this line and increment the number 0 to the next integer. The script is written in Perl but I could just as easily use awk or sed.

I would like to trigger the script automatically in git when a branch is merged to master. I thought a server-side hook would be the right approach. However, I'm not sure if this is the best approach?

For example, does it require a git commit or git add to be executed on the master branch? Assuming it is the best approach, can you recommend the appropriate type of hook. Or are there better ways to solve the same problem?

Answer Source

There is one hook, post-merge, that can be invoked by git merge. But it works in the local repo.

If you want Git to track down the change, yes, you need add and commit it. This is not proper to be done in the remote repo.

In this hook, you can check if the current branch is master. If yes, make the change, add and commit. If not, just do nothing else.

No option of git merge can bypass this hook once it's deployed, which might be annoying sometimes. If case you want to disable the hook, there are some approaches to do the job. Set a flag variable reachable inside the hook, check its value and go on. You could export an environment variable before git merge and unset it afterwards. Or, you could set a self-defined config key. For example, git config true or git config false beforehand. In the hook, check the value of git config --get Another method is to change the hook's name, like mv .git/hooks/post-merge .git/hooks/post-merged. Change it back when you need it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download