'How can I make a git hook to update the npm patch version on every commit or merge to master?

TLDR version of my question:

What I want is that doing work and committing things to feature branches (anything non-master) doesn't touch the version number, but committing or merging into master does. The version number is in package.json.

What should the setup for this look like?

The long version (what I've tried)

In trying to automate version numbers, I've found that doing npm version patch will bump the version in the package.json file, which is one part of what I'm trying to do. And then playing with the sample hooks in git's .git/hooks directory, I found that they are just shell scripts that fire on various events, which is great, and they are the second part of what I'm trying to do.

But I can't figure out how to connect them.

Obstacle number 1 is that npm version patch seems to want to do a commit and a tag, and so doing it together with the work that I'm already committing (as a pre-commit hook) fails with an error message saying "Git working directory not clean".

What I want is that it just also bumps the version along all of the changes that I'm already committing (or merging), instead of creating a brand new commit and a tag, so that I avoid having my commit history being plagued by commit messages that are just the version number on every other commit.

Obstacle number 2 is very simply that the pre-merge-commit hook doesn't seem to fire. I've tested the pre-commit hook by just echoing a message and then exiting with 1, which works; But as a pre-merge-commit (and then doing a merge), the merge just succeeds without my hook stopping it.

So I don't know what I'm doing wrong and how to connect these two things to work with each other.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source