Git Hooks error when using NVM in WebStorm and SourceTree

Viewed 2252

I'm using nvm with the --no-use flag as that was causing my terminal to start massively slow . That means than I always need to run nvm use <NODE_VERSION> on new terminal tabs in order to be able to use node or npm.

I have a project with some Git Hooks configured using ghooks, so each time I move to a different branch or commit something, I get different type of errors in both WebStorm and SourceTree, all pointing oout that node could not be found. These are some of them:

SourceTree checkout:

git -c diff.mnemonicprefix=false -c core.quotepath=false -c 
credential.helper=sourcetree checkout BRANCH
Switched to branch 'BRANCH'
M   ...
M   ...
...
env: node: No such file or directory
Completed with errors, see above

WebStorm commit:

Commit failed with error
0 files committed, 3 files failed to commit: COMMIT_MESSAGE env: node: No such file or directory

In WebStorm, I thought that manually setting the node version to use (under Preferences > Languages & Frameworks > Node.js and NPM > Node interpreter) would fix the issue, but it didn't.

I'm using WebStorm 2016.1.3, Build #WS-145.1616.

Removing the --no-use flag would fix it of course, but that's not an option as then the terminal becomes super slow at startup. Any other way to get around that?

2 Answers

Consider using husky (maybe also with lint-staged) to get more control over how your Git hooks are executed. Basically, you could have all your hooks nicely defined as NPM commands in the package.json of the project. Since it all goes into Git hooks, they'll be executed with GUI clients like IDE or SourceTree, at the end.

The issue seems to be related to the system using different paths for the terminal & GUI applications (e.g. WebStorm or SourceTree). With husky, you could just define a ~/.huskyrc and write down what Node version to use, or source nvm for that beforehand. I also use nvm, and the config taken from their Readme just works as-is:

# ~/.huskyrc
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

NB. I'm not affiliated with husky anyhow, just enjoying the way it works.

Git hooks is calling node from a non-interactive shell so it's not using the shell environment you probably set in your .bashrc file after installing nvm.

Try adding this: . $HOME/.nvm/nvm.sh to your .git/hooks/pre-commit file

in the end it should look similar to:

#!/bin/bash
. $HOME/.nvm/nvm.sh
./node_modules/pre-commit/hook
RESULT=$?
[ $RESULT -ne 0 ] && exit 1
exit 0
Related